c - 如何重新启动程序而不保存其值 (C)

标签 c function loops while-loop

我正在尝试制作一个可以读取和计算数字有多少位的程序,这是我到目前为止的代码

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

int main(){
   int a, b=0;
   printf("Hey welcome to how many digits your number has!\n");
   xyz:
   printf("To begin enter a Number = ");
   scanf("%d",&a);

   while (a!=0) {
    a/=10;
    ++b;
   }

   printf("your number has %d digits\n",b);
   int choice;
   printf("do you want to use another number?\nIf yes enter \"1\"\nif no enter \"2\"\n");
   scanf("%d",&choice);

   if (choice==1){
    goto xyz;
   }

   else if (choice==2){
    return 0;
   }

return 0;
}

这在第一次时效果很好,但是当我返回并重复时,似乎上次尝试中的“b”值已被存储。 如何重新开始而不存储变量“b”的值并保持 b = 0 的值?

最佳答案

这是因为您的 goto 不包含 b = 0 的初始化

xyz:
b = 0;

强烈建议您忘记goto关键字。它很容易导致不可读和不可调试的代码。尝试使用循环:

int main()
{
   int choice = 1;
   while (choice == 1)
   {
       int a, b = 0;
       printf("Hey welcome to how many digits your number has!\n");
       printf("To begin enter a Number = ");
       scanf("%d", &a);

       while (a != 0)
       {
           a /= 10;
           ++b;
       }

       printf("your number has %d digits\n",b);
       //removed declaration of choice
       printf("do you want to use another number?\nIf yes enter \"1\"\nif no enter \"2\"\n");
       scanf("%d", &choice);
    }
    return (0);
}

关于c - 如何重新启动程序而不保存其值 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649196/

相关文章:

c - 如何将输出视频保存到 OpenCV 中的文件中

c - as400 : what is the C equivalent of SNDRCVF

c++ - 在Linux上安装gcc

快速停止循环并使用按钮继续

java - 与另一个列表相比更新列表元素的快速方法

c - 为什么 putchar() 打印出带有 "%"符号的字符?

函数精确度和召回率

python - 单击按钮的返回值

c++ - 在类函数方法中将值存储在缓冲区中

java - 包含循环的静态方法是线程安全的吗?