为什么我的 int 输出与预期不同?

0 c++ integer

我的bin倒数第二行显示了类似的内容,3282692812当它意味着不同时。其他都很好,我尝试过在网上搜索,但找不到任何相关信息。

string a;
int amount;
cout << "1-10k 2-2k 3-1k: ";
cin >> a;
cout << "\n";
cout << "How many numbers do you want to be generated?: ";
cin >> amount;
cout << "\n";
long bin = 0;



if (int(a) = 1)
{
    bin = 60457811425;
}
else if (a == 2)
{
    bin = 60457811474;
}
else if (a == 3)
{
    bin = 6045781165;
}

for (int i = 0; i < amount; i++)
{
    cout << bin << rand() % 10 << rand() % 10 << rand() % 10 << rand() % 10 << rand() % 10 << rand() % 10 << "|" << setw(2) << setfill('0') << rand() % (13 - 1) + 1 << "|" << rand() % (2031 - 2022) + 2022 << "|" << setw(3) << setfill('0') << rand() % 999 << "\n";
}

system("pause");
Run Code Online (Sandbox Code Playgroud)

Sha*_*ger 5

你只转换aint一次,你没有使用合法的转换器来做到这一点(int从 a “构造” anstd::string不能像那样工作,如果你的编译器没有警告你,我会感到惊讶),并且你分配给结果 ( =) 而不是比较( ==) (也是我希望编译器警告您的事情)。

后来检查了这些警告:碰巧,它看起来像gcc同时接受两个构造作为完全不同的构造(它解释if (int(a) = 1)声明一个名为 的影子int变量a,初始化为,在/链1后过期;这很有趣)。如果您使用 进行编译,它只会发出警告,即使如此,它也只会抱怨,因为它认为应该使名称遮蔽变量没有无关的括号,呃。好的一面是,将作业固定为比较将揭示另一个问题。这是始终在出现警告的情况下进行编译的一个很好的理由(有时过于啰嗦,但几乎总是指出真正的问题),遗憾的是在这种情况下这是一个相当间接的警告。ifelse if-Wallif (int a = 1)-Wextra-Wall

使用有效的string转换int器(例如 )std::stoi预先将其转换一次,然后int针对其他int值(而不是std::string针对 )测试转换后的值int,例如:

const int aint = std::stoi(a);
if (aint == 1)  // Using ==, not =
{
    bin = 60457811425;
}
else if (aint == 2)  // Testing int == int, not string == int
{
    bin = 60457811474;
}
else if (aint == 3)  // Testing int == int, not string == int
{
    bin = 6045781165;
}
Run Code Online (Sandbox Code Playgroud)

或者对于稍微简洁的代码(并且没有额外的命名变量):

switch(std::stoi(a)) {
    case 1: bin = 60457811425; break;
    case 2: bin = 60457811474; break;
    case 3: bin = 6045781165; break;
    /* Maybe put a default case here to handle invalid input? */
}
Run Code Online (Sandbox Code Playgroud)