如何在不保存程序值的情况下重新启动程序(C)

时间:2018-12-06 10:22:52

标签: 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的情况下重新开始?

2 个答案:

答案 0 :(得分:2)

这是因为您的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);
}

答案 1 :(得分:0)

最明显的错误是,b标签内的零件内部的0没有重新初始化为xyz。因此,这些值只是不断累加,而不是为新输入开始计数。因此解决方法是:

xyz:
b = 0;

但是建议不要使用goto,因为它容易产生混乱的代码,并可能导致无限循环。请参阅下面的这篇文章:

Why should you avoid goto?

改为使用whiledo-while ...,如下所示:

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

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

   while (a!=0) {
    a/=10;
    ++b;
   }
             // removed declaration of choice from here and placed it along with other declarations in main()
   printf("your number has %d digits\n",b);
   printf("do you want to use another number?\nIf yes enter \"1\"\nif no enter \"2\"\n");
   scanf("%d",&choice);
   }while(choice == 1); //repeat the process again if user inputs choice as 1, else exit

return 0;
}