📜  C++ 程序的输出 |设置 42

📅  最后修改于: 2022-05-13 01:56:11.173000             🧑  作者: Mango

C++ 程序的输出 |设置 42

先决条件:指针和引用

Q.1 这个程序的输出是什么?

#include 
using namespace std;
void fun(int& a, int b)
{
    a += 2;
    b += 1;
}
int main()
{
    int x = 10, y = 2;
    fun(x, y);
    cout << x << " " << y << " ";
    fun(x, y);
    cout << x << " " << y;
    return 0;
}

选项
a) 10 2 10 2
b) 12 2 14 2
c) 12 3 14 3
d) 12 2 14 3

Answer : b

说明:在这个程序中,在 main() 中,我们在 fun() 和 fun() 中传递两个值 x 或 y 接收到 x 的引用,因此增加它的值,但 y 增加了但不是引用,所以 y 在主块中是相同的。

Q.2 这个程序的输出是什么?



#include 
using namespace std;
void f2(int p = 30)
{
    for (int i = 20; i <= p; i += 5)
        cout << i << " ";
}
void f1(int& m)
{
    m += 10;
    f2(m);
}
int main()
{
    int n = 20;
    f1(n);
    cout << n << " ";
    return 0;
}

选项
a) 25 30 35 20
b) 20 25 30 20
c) 25 30 25 30
d) 20 25 30 30

Answer : d

说明:在这个程序中,main() 调用 f1() 并在 f1() 中传递 n 的值,f1() 接收到 n 的引用并将其值增加 10,现在 n 是 30。再次调用 f2()并在 f2() 中传递 m 的值,f2() 接收 m 的值并检查条件并打印该值。

Q.3 这个程序的输出是什么?

#include 
using namespace std;
void fun(char s[], int n)
{
    for (int i = 0; s[i] != '\0'; i++)
        if (i % 2 == 0)
            s[i] = s[i] - n;
        else
            s[i] = s[i] + n;
}
int main()
{
    char str[] = "Hello_World";
    fun(str, 2);
    cout << str << endl;
    return 0;
}

选项
a) EgjnmaTqpnb
b) FgjnmaUqpnb
c) Fgjnm_Uqpnb
d) EgjnmaTqpnb

Answer : b

说明:在 main() 中,调用 fun() 并传递字符串和一个整数是 2。在 fun() 中,循环 i 被迭代并检查条件,如果 i 是偶数,则将索引值减 2,如果 i 是奇数,则增加2。

Q.4 这个程序的输出是什么?

#include 
using namespace std;
int main()
{
    int x[] = { 12, 25, 30, 55, 110 };
    int* p = x;
    while (*p < 110) {
        if (*p % 3 != 0)
            *p = *p + 1;
        else
            *p = *p + 2;
        p++;
    }
    for (int i = 4; i >= 1; i--) {
        cout << x[i] << " ";
    }
    return 0;
}

选项
a) 110 56 32 26
b) 110 57 30 27
c) 110 56 32 25
d) 100 55 30 25

Answer : a

说明:在这个程序中,指针 p 包含数组 x 的基地址,所以 *p 包含 x[0] 的值,而 p++ 是指向下一个元素的地址。

Q.5这个程序的输出是什么?

#include 
using namespace std;
int main()
{
    char* str = "GEEKSFORGEEK";
    int* p, arr[] = { 10, 15, 70, 19 };
    p = arr;
    str++;
    p++;
    cout << *p << " " << str << endl;
    return 0;
}

选项
a) 10 EEKSFORGEEK
b) 15 GEEKSFORGEEK
c) 15 EEKSFORGEEK
d) 10 GEEKSFORGEEK

Answer : C

说明:在此,str 包含字符串的基地址,指针 p 包含数组的基地址。如果字符串和指针加 1 - 它指向字符串和数组的下一个地址值。