【发布时间】:2018-12-19 21:45:59
【问题描述】:
我的程序可以正常处理最多 10 位的数字,但是当我使用hackerrank 编译器时,任何数字都会导致它输出错误的数字。但是,当我使用 Visual Studio 时,它没有输出任何内容,但我听到某些东西一直在旋转,直到我关闭 cmd 窗口(可能是 CPU)。
#include <bits/stdc++.h>
using namespace std;
int main()
{
// This program counts the "a" letters in a string (s) depending on how
// many iterations(numOfRepetitions) through the string
string s;
getline(cin, s);
int64_t numOfRepetitions;
cin >> numOfRepetitions;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
int64_t i=0;
int64_t countA=0; // Counting occurances of letter "a"
for (int64_t x=0; x<numOfRepetitions; x++)
{
if (s[i]=='a') countA++;
if (i==s.length()-1) i=-1;
i++;
}
cout << countA << endl;
}
// Input that works: s = 'a' numOfRepetitions=1000 Output:1000
// Input doesn't work: s = 'a' numOfRepetitions=1000000000000
// Output:1410065408 ( it should be: 1000000000000 )
注意:我在其他线程中尝试了使用 long long、int32_t、casting as double ... 等的建议。没有任何效果
【问题讨论】:
-
for (int x=0; x<numOfRepetitions; x++)如果你打算在一个地方使用 int64_t,你需要在所有地方都使用它。读完后把号码打印出来。如果它就在那里,但您的程序不起作用,那么问题出在其他地方。 -
“我听到一些东西一直在快速旋转,直到我关闭 cmd 窗口(可能是 CPU)” 那是风扇。不过,这表明 CPU 正在努力工作
-
signed整数溢出是未定义的行为。您的程序很可能正在旋转您的 CPU。 -
你有没有想过你做错了。计算字符串中a的数量一次,然后相乘。 a 的数量不会改变。
-
也许 OP 在 c++11 之前的平台上,
std::cin不需要有operator>>(long long&)并且使用的是窄类型?
标签: c++ visual-studio c++11 visual-c++ c++14