C 程序错误(没有完全退出循环?)
Error in C Program (not fully exiting loop?)
这个程序应该读取用户输入的数字并检查重复的数字。该程序一直要求输入数字,直到用户输入任何小于或等于 0 的数字。它的主要工作原理是,如果您输入重复的数字,它会告诉您。但是,如果您从另一个号码呼叫中输入相同的数字,则它被视为重复数字。例如,如果在一个实例中输入 23,然后在另一个实例中输入 52,它会认为存在重复(即使在新输入的数字中没有)。关于如何修复它有什么想法吗?
#include <stdio.h>
#include <stdbool.h> //as per C99 standard
int main (void)
{
bool digit_seen[10] = {false};
int digit;
long n;
while (1){
printf("Enter a number (enter 0 to terminate the program): ");
scanf("%ld", &n);
if (n == 0){
break;
}
while (n > 0){
digit = n % 10;
if (digit_seen[digit]){
break;
}
digit_seen[digit] = true;
n /= 10;
}
if (n > 0){
printf("Repeated digit\n");
} else {
printf("No repeated digit\n");
}
}
return 0;
}
However if you enter the same digit from another number call, it is considered a repeat digit.
就目前而言,digit_seen
仅初始化一次,在 while
循环之外 ,它从未为新输入重新初始化 n
.
您需要将此代码 bool digit_seen[10] = {false};
移动到 内部 您的 while
循环。这将解决问题。
这个程序应该读取用户输入的数字并检查重复的数字。该程序一直要求输入数字,直到用户输入任何小于或等于 0 的数字。它的主要工作原理是,如果您输入重复的数字,它会告诉您。但是,如果您从另一个号码呼叫中输入相同的数字,则它被视为重复数字。例如,如果在一个实例中输入 23,然后在另一个实例中输入 52,它会认为存在重复(即使在新输入的数字中没有)。关于如何修复它有什么想法吗?
#include <stdio.h>
#include <stdbool.h> //as per C99 standard
int main (void)
{
bool digit_seen[10] = {false};
int digit;
long n;
while (1){
printf("Enter a number (enter 0 to terminate the program): ");
scanf("%ld", &n);
if (n == 0){
break;
}
while (n > 0){
digit = n % 10;
if (digit_seen[digit]){
break;
}
digit_seen[digit] = true;
n /= 10;
}
if (n > 0){
printf("Repeated digit\n");
} else {
printf("No repeated digit\n");
}
}
return 0;
}
However if you enter the same digit from another number call, it is considered a repeat digit.
就目前而言,digit_seen
仅初始化一次,在 while
循环之外 ,它从未为新输入重新初始化 n
.
您需要将此代码 bool digit_seen[10] = {false};
移动到 内部 您的 while
循环。这将解决问题。