这是我关于堆栈溢出的第一篇文章,所以这是我到目前为止的代码,我刚刚开始计算机工程,遇到了一些麻烦。
#include <stdio.h>
int main ( void ) {
int num, sum = 0, i, ssq = 0, isq, n;
printf("Enter an integer: ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
sum = sum + (i * i);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
while (i >= 0) {
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
printf("Enter an integer: ");
scanf("%d", &num);
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
if (i == 0) break;
}
return 0;
}
这就是我到目前为止所相信的,不管你相信与否,我花了 12 个小时来完成第一部分,在 while
循环之前和现在,我确实整晚都在为此工作我完全迷路了。我添加了 ssq=0
、isq
和 n
整数来尝试帮助但无济于事。在这一点上,我只是连续几个小时重新整理东西,这是我的第一篇文章,所以请不要对我太苛刻!
最佳答案
正如@HappyCoder 上文所述,这包含大量错误,从拼写错误到代码重复。
首先,外部部分和循环部分做的完全一样。想一想。您首先无条件地执行一些任务,然后询问用户是否要重新开始。任务本身不会改变!因此,我们可以做的是:
do the task;
ask the user if they want to quit or go on;
if yes, return to the start.
在代码中,这可以通过一个无限循环来完成,如果用户想要停止,您可以跳出这个循环:
while(1) {
// do user input and calculations here;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
if (i == 0)
break;
}
看,现在我们只有一个计算代码的实例!现在,您可以丢弃开头声明的一半变量,因为它们是重复的。
现在进行计算。循环中有一个未初始化的变量 ssq
。看看代码重复会把你带到哪里。在外部,它被正确初始化。然而,在循环内部,不能保证它包含任何具体值,很可能它包含垃圾。
另外,正如@JohnHascall 所指出的,这个细微的错误很可能是由打字错误引起的:
for (isq = 1; isq <= n; isq++); // <---- the evil semicolon
ssq = ssq + (isq * isq);
for
循环后的分号使循环为空,求和只发生一次,但不在循环中,正如您希望的那样。
然后,你在循环内部输出(print)sum
而不是ssq
,这显然不是你想要打印的。 并且,您使用循环外部未初始化的n
变量作为边界,而不是用户输入的num
。
我想再添加一个。明智地命名变量很重要,因为它可以帮助您发现潜在的错误并跟踪变量在整个代码中的使用方式,更不用说其他人更容易理解代码了。看:int i
-> int choice
不是更好吗?
所以我们可以像这样重写代码:
#include <stdio.h>
int main ( void )
{
int boundary, choice, isq, ssq;
while (1) {
printf("Enter an integer: ");
scanf("%d", &boundary);
ssq = 0;
for (isq = 1; isq <= boundary; isq++) {
ssq = ssq + (isq * isq);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", boundary, ssq);
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
if (choice == 0)
break;
}
return 0;
}
关于c - 向我的 c 程序添加一个外部 while 循环 - 初学者 1 继续 0 停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35411471/