c - 有什么办法可以使这个添加无限?

标签 c

所以我试着让这成为用户输入的无限循环并添加它。但它只是在最后结束。请帮忙

#include <stdio.h>
#include <stdlib.h>

int SUM(int a)
{
  int sum = 0;
  while (a > 0) 
  {
    sum = sum + (a % 10);
    a = a / 10;
  }
  return sum;
}

int main()
{
  int x;
  printf("Enter an integer = ");

  scanf("%d", &x);

  SUM(x);

  printf("Sum digit = %d", SUM(x));
}

最佳答案

只需像这样在主函数中添加一个无限循环:

#include <stdio.h>
#include <stdlib.h>

int SUM(int a){
int sum=0;
while(a>0){
    sum =sum+(a%10);

    a=a/10;

}

return sum;
}

int main(){
    int x;
    char quit = 'n';
    do{
        printf("Enter an integer = ");

        scanf("%d", &x);

        printf("Sum digit = %d", SUM(x));

        //exiting option 
        printf("Quit the program? [y/n]");
        scanf(" %c",&quit);
    }while(quit !='y' && quit != 'Y');   
}

此外,在 printf 之前包含 SUM(x) 函数的行是多余的。

编辑:我插入了一个选项以在每次迭代结束时退出无限循环 - 如果您不想要该选项,只需将其更改为 while(1) 并删除打印和结束前的 scanf 命令。

关于c - 有什么办法可以使这个添加无限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146818/

相关文章:

c - 使用递归时如何避免初始化变量?

c - 2 的补码中的 16 位值,令人困惑

c - 我不明白 C 中二叉树中的函数

c - 了解 gcc 4.9.2 自动矢量化输出

c - OpenGL 在使用使用它制作的 dll 时给出异常

c - 如何在不打开文件的情况下判断/proc/[pid]/status 是否已更改

c 结构体和 pthread 指针分配

c - 用户在 scanf 中键入空终止符

函数调用中未填充 C 字符串

c - 等待所有子进程创建 - C