通过使用while循环找到n个自然数的总和获得不良结果

时间:2018-08-16 16:30:05

标签: c while-loop

我附加了相同的代码。它可以正常工作。但是,一旦输入的数字小于前一个数字,它将停止提供所需的输出。任何帮助/建议都将不胜感激。

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;

5 个答案:

答案 0 :(得分:2)

在外部while循环中,您永远不会将变量i的值重置为1j重置为0。这就是为什么后续循环将产生不正确的总和的原因。

答案 1 :(得分:1)

此代码中包含一些错误,包括:

  1. 与初始ch表达式中while的未初始化值进行比较。
  2. 每次外部循环迭代均无法重置ij
  3. 在任一scanf调用中未能测试数据读取是否成功,以确保输入正确。
  4. 对于具有跳过空格的单个字符,连续{​​{1}}完全是错误的(必须这样做,以避免在输入列表整数后读取换行符)。除非达到EOF或错误状态,否则将为您提供保证来调用未定义的行为,因为字符串读取至少一个字符需要至少两个进行存储(字符以及后续的终止符)。

解决所有这些问题:

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重设jn

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,所以它没有进入循环并打印先前的值。