【问题标题】:How to restart program without it saving its values (C)如何在不保存其值的情况下重新启动程序(C)
【发布时间】:2018-12-06 10:22:51
【问题描述】:

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

#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,我该如何重新开始?

【问题讨论】:

  • b=0放在xyz下面
  • 不错的努力。尝试在不使用goto 的情况下考虑不同的解决方案。在代码中使用goto 不是一个好习惯。快乐编码:)
  • goto 的用处很少。这都不是。使用循环,意大利面属于带有好酱汁的盘子。

标签: c function loops while-loop


【解决方案1】:

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

【讨论】:

  • 非常感谢!正是在寻找什么谢谢!
  • do ... while 会在输入0 时捕获角盒。
  • 我建议不要使用 return (0); 而不是 return 0;。它使它看起来像一个函数调用。看到这个:stackoverflow.com/questions/161879/…
  • @Jabberwocky 我一直习惯于使用括号作为返回值。正如链接的接受答案中所述,“括号成为一种习惯并且卡住了。”
【解决方案2】:

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

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;
}

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2021-10-06
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多