【问题标题】:Why does my int output something different than what it's supposed to?为什么我的 int 输出的东西与它应该输出的不同?
【发布时间】:2022-07-06 02:11:15
【问题描述】:

我的倒数第二行中的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");

【问题讨论】:

  • 如果显示的bin 值不正确,您可以删除所有对rand() 的调用,因为它们只是分散注意力。此外,不需要多次显示它。
  • 请澄清您所说的“当它意味着不同时”是什么意思。您期望该程序的输出是什么?

标签: c++ integer


【解决方案1】:

您只将a 转换为int 一次,您没有使用合法的转换器进行此操作(从std::string“构造”int 不能这样工作,而且我'如果您的编译器没有警告您,您会感到惊讶),并且您分配到结果(=)而不是比较==)(也是我'希望编译器会警告你)。

先将其转换一次with a valid string to int converter like std::stoi,然后将转换后的int 值与其他ints 进行对比,而不是std::stringint 对比,例如:

const int aint = std::stoi(a);
if (aint == 1)  // Using ==, not =, and testing int == int, not string == int
{
    bin = 60457811425;
}
else if (aint == 2)
{
    bin = 60457811474;
}
else if (aint == 3)
{
    bin = 6045781165;
}

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

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? */
}

【讨论】:

  • @PeteBecker:糟糕,谢谢。在其他问题中没有注意到它,将明确解决。
  • @PeteBecker:已解决/已修复。
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2013-08-30
  • 2021-12-11
  • 2020-09-03
  • 1970-01-01
  • 2020-10-01
  • 2021-05-10
  • 2017-01-06
相关资源
最近更新 更多