在这个文件中,我试图制作一些东西,将所有数字添加到用户输入的数字。例如,4:1 + 2 + 3 + 4 = 10.因此,如果他们输入4则返回10.
当我运行代码时,我收到一条错误消息,指出我的文件已停止工作。我有无限循环吗?
#include "biglib.h"
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
// Asking them for their number
int num;
scanf("%i", num);
// then I run a loop, if num == 0 then the program should break from the loop and return 0 in the main function if not run the code inside the program.
int i;
while(num != 0)
{
// I define "i" to be one less than that of num then as long as "i" is greater than 0 keep running the loop and subtract one at the end of it.
for(i = num - 1; i > 0; i--)
{
// in here I do the addition.
num = num + i;
}
// finally I print out the answer.
printf("%i\n",num);
continue;
}
return 0;
}
答案 0 :(得分:1)
是的,你有一个无限循环。输入也不存储在num
变量中。
#include "stdio.h"
int main(void) {
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
scanf("%i", &num);
int sum = 0;
while(num>0){
sum += num;
num -= 1;
}
printf("%i\n",sum);
return 0;
}
答案 1 :(得分:0)
你的代码中有些行对我来说很奇怪。 为什么使用while循环来测试num的值? 为什么将continue语句作为最后一个while循环指令?
说明: 您的代码不适用于负数,是否是预期的行为? 您没有测试scanf返回值,这可能会导致麻烦。 我很确定你应该检查一下scanf原型。
希望这些问题可以帮助您改进代码。
答案 2 :(得分:0)
谢谢yadras告诉我,我在while循环之外的scanf是问题,现在它可以正常工作。
int main()
{
puts("Enter any number and it will return all the numbers from 1 to your number added together.");
int num;
int i;
while(num != 0){
scanf("%i", &num);
for(i = num - 1; i > 0; i--)
{
num = num + i;
}
printf("%i\n",num);
}
return 0;
}