我在哪里初始化我的整数重要吗?

Does it matter where I initialize my integer?

我想明白一些事情。我仍然是 c++ 的初学者,我刚刚创建了这个小程序,您可以在其中输入一个值,它会告诉您它是偶数还是奇数。为此,我创建了一个名为 "result" 的整数,它取值,然后执行 % 2 操作。

但是,我的第一个错误是我将 int result 放在 "cin >> value" 上面,所以出于某种原因搞砸了程序,无论如何数字总是偶数。然后,当我将 int result 放在 "cin >> value" 下面时,程序会正常运行。为什么要这样做?

如有任何帮助,我们将不胜感激。如果这是重复的,我很抱歉,但我不知道要搜索什么。

#include <iostream>
#include <string>
#include "Human.h"
#include <ctime>
using namespace std;



int main() {


    int value = 0; // where I input
    cin >> value;
    // if you put int result above cin program changes.
    int result = value % 2;

    if (result == 0) {
        cout << "Even number." << endl;
    }
    else {
        cout << "Odd number." << endl;
    }



    return 0;
}

无论您使用哪种编程语言,任何代码都是从上到下运行的。 您需要先声明变量,给它一个值,然后检查是偶数还是奇数。

当您在设置 result = value%2; 的值后使用 cin 时,编译器使用 value 的初始初始化值 0 来计算 result 的值将是 0%2.

这就是为什么您需要在设置 result = value%2; 之前使用 cin>>value;

C++ 从上到下逐行阅读代码。因此,如果你想阅读它,你将不得不对你的变量进行 int first.I 制作一个更简单的程序版本:

#include <iostream>

using namespace std;

int main() {
int a;
cout << "a=";
cin >> a ;

if(a%2==0)
    {cout<<"a is even";}
else
    {cout<<"a is uneven";}
}

当您将 int result = value % 2; 放在 cin >> value; 之前时,您的程序将在您通过输入将值放入 int value 之前计算结果。 所以你的程序确实计算了 int result = 0 % 2;