问题描述
源代码如下。
#include <stdio.h>
int main()
{
long long n;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld",&n);
//kNow that enterd interger(contact number) have how many numbers in it
while (n != 0) {
n /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",n);
return 0;
}
在这段代码中,我尝试输入用户的联系电话,并检查您的联系电话中有多少个数字,然后您的联系电话中有10个数字,所以它是正确的,但数字不是10个它显示错误并再次输入用户的号码。当号码正确时程序打印用户联系号码 0。 请指导我这段代码有什么问题?
解决方法
您所做的是在 while 循环中将 n 的值更改为 0 并在最后打印相同的 n。这就是它打印 0 的原因。 您可以做的是,您可以使用一个临时变量来计算字符数。参考以下代码:
#include <stdio.h>
int main()
{
long long n,temp; //taking a temporary variable along with n;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld",&n);
temp = n; // assigning n to temp variable
//know that enterd interger(contact number) have how many numbers in it
while (temp != 0) { //counting the number of digits using temp variable.
temp /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",n);
return 0;
}
,
问题在于语句 n /= 10;
此处您使用了赋值运算符,因此它会更改 n
的值。
例如,如果您输入 n
作为 9876543210
,那么在第一次迭代后,n
的值将是 9876543210/=10 i.e. 987654321
。这样,在所有迭代之后,n
的值将是 0
。
您可以使用临时变量来存储 n
值并打印它。
#include <stdio.h>
int main()
{
long long n,m;
int count;
lable:
count = 0;
printf("Enter your contact number : ");
scanf("%lld",&n);
m = n;
//know that enterd interger(contact number) have how many numbers in it
while (n != 0) {
n /= 10;
++count;
}
//if numbers are 10 then your contact number is right
if(count==10)
{
printf("contact number enterd sucessfully\n");
goto exit;
}
else
//else numbers are not 10 then invalid contact number and enter again
{
printf("In valid contact number enter again...........\n");
goto lable;
}
exit:
printf("contact number : %lld ",m);
return 0;
}
,
思考这部分:
while (n != 0) {
n /= 10;
++count;
}
您在这里所做的更改了您从用户那里扫描的 n
的值。所以你可以做的不是使用变量 n
而是复制它并使用它。 这里的一个好做法是使您不想意外编辑的变量恒定。