我正在尝试制作一个可以读取和计算数字有多少位的程序,这是我到目前为止的代码
#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/