我附加了相同的代码。它可以正常工作。但是,一旦输入的数字小于前一个数字,它将停止提供所需的输出。任何帮助/建议都将不胜感激。
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
答案 0 :(得分:2)
在外部while
循环中,您永远不会将变量i
的值重置为1
或j
重置为0
。这就是为什么后续循环将产生不正确的总和的原因。
答案 1 :(得分:1)
此代码中包含一些错误,包括:
ch
表达式中while
的未初始化值进行比较。i
和j
scanf
调用中未能测试数据读取是否成功,以确保输入正确。解决所有这些问题:
scanf("%s", &ch)
当提到上一个错误打孔列表时,这里的所有内容都是不言自明的,可能除了用于读取单个字符的格式字符串以外。您在注释中提到尝试过#include <stdio.h>
int main()
{
char ch;
do
{
int n;
printf("Enter the number upto which you want the sum of \n \n");
if (scanf("%d", &n) != 1) // See (3)
break;
int j = 0; // See (2)
for (int i = 1; i <= n; ++i) // See (2)
j += i;
printf("%d \n", j);
printf("Do it with another number? Y/N \n \n");
if (scanf(" %c", &ch) != 1) // See (3) and (4)
break;
} while (ch != 'n' && ch != 'N'); // See (1)
return 0;
}
,但是它跳到了另一个循环迭代。这是因为您没有开头的空格%c
告诉" %c"
在提取下一个参数之前要跳过空格。这样,它应该可以正常工作。
答案 2 :(得分:0)
您需要为每个i
重设j
和n
。
i = 1;j=0;
while(i<=n)
{
您的格式说明符也是错误的。对于char
,它应该是%c
而不是%s
scanf("%c",&ch);
答案 3 :(得分:0)
最简单的解决方案是在外部i
上将while
设置为0:
int i=1;
int j=0;
int n;
char ch;
while(ch!='n')
{
i = 0;
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
while(i<n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%s",&ch);
}
return 0;
请注意,我已经将<=
更改为<
,因为如果您一个接一个地输入相同的n
,则您不想增加该值。
答案 4 :(得分:0)
#include<stdio.h>
int main(){
int n;
char ch;
while(ch!='n')
{
printf("Enter the number upto which you want the sum of \n \n");
scanf("%d",&n);
int i=1;//it should be 1 in every loop of the number
int j=0;//the sum should also be initialized to zero to erase the previous value
while(i<=n)
{
j=j+i;
i++;
}
printf("%d \n",j);
printf("Do it with another number? Y/N \n \n");
scanf("%c",&ch);//this is a char not a string
}
return 0;
}
由于当第二次进入循环时i并未初始化为1,所以它没有进入循环并打印先前的值。