我有一个程序,应该对文本文件中的数字(而不是数字!)求和。
就像这样:
(我会迭代字符串)
char str[] = "some random stuff with numbers 20001, 20002, 20003";
int count = 4; //length of number eg. 4
while(count > -1)
{
num += (str[i - count] - '0') * (int)pow(10, count);
count -= 1;
printf("%i \n", count);
if(count < 0)
break;
}
运行6次
计数= 4,3,2,1,0,0
要检查我是否愚蠢,我添加了printf语句,它实际上说count是-1,它仍然会重复一次,但只会重复一次,并非在每种情况下都重复一次。大约50%(不交替)。
首先我有for循环...不起作用。
然后我将count--改为-= 1 ...同样。
然后我添加了if语句...也不起作用。
如果您想阅读整个代码:
https://pastebin.com/X3wCs4cF(部分内容是德语的,因为我是从那里来的,此任务要求我以这种方式编写)
Glhf
答案 0 :(得分:1)
您忘记初始化count
:
int count; // defined, but not initialized
while(count > -1) // undefined behaviour here; accessing an uninitialized value
这应该有效:
int count = 5;
while(count > -1) ...