为数字添加条件的程序
Program to add condition to digits
我编写了一个程序来输入 4 位数字并打印第 1000、100、10 和个位的数字。我想添加一个条件,如果用户输入的数字多于或少于 4 位,则输出应为 Only 4-digits are allowed.
#include<stdio.h>
int main(){
int a, th, h, t, u;
printf("Enter a 4-digit number: ");
scanf("%d", &a);
u = a%10;
t = (a/10)%10;
h = (a/100)%10;
th = (a/1000);
printf("\nThousands = %d, Hundreds = %d, Tens = %d, Units = %d\n", th, h, t, u);
return 0;
}
怎么办?
您可以试试下面的代码
if(a<1000 || a>9999)
{
printf("Only 4-digits are allowed:");
}
这取决于“0999”是否被视为4位数字。如果不是,那么任何已发布的解决方案都可以使用。如果是,则必须将输入扫描为字符串,以便在将其转换为 int 之前测试其长度。你也可以走这条路:
char digits[5];
scanf("%c%c%c%c", &digits[0], &digits[1], &digits[2], &digits[3]);
digits[4] = '[=10=]'; // terminate the character array.
for(int i=0; i<4; i++) {
if (digits[i] < '0' or digits[i] > '9') {
//throw a fit at the user and return
}
}
printf("thousands: %c, hundreds: %c, tens: %c, ones: %c\n", digits[0].... etc.);
我编写了一个程序来输入 4 位数字并打印第 1000、100、10 和个位的数字。我想添加一个条件,如果用户输入的数字多于或少于 4 位,则输出应为 Only 4-digits are allowed.
#include<stdio.h>
int main(){
int a, th, h, t, u;
printf("Enter a 4-digit number: ");
scanf("%d", &a);
u = a%10;
t = (a/10)%10;
h = (a/100)%10;
th = (a/1000);
printf("\nThousands = %d, Hundreds = %d, Tens = %d, Units = %d\n", th, h, t, u);
return 0;
}
怎么办?
您可以试试下面的代码
if(a<1000 || a>9999)
{
printf("Only 4-digits are allowed:");
}
这取决于“0999”是否被视为4位数字。如果不是,那么任何已发布的解决方案都可以使用。如果是,则必须将输入扫描为字符串,以便在将其转换为 int 之前测试其长度。你也可以走这条路:
char digits[5];
scanf("%c%c%c%c", &digits[0], &digits[1], &digits[2], &digits[3]);
digits[4] = '[=10=]'; // terminate the character array.
for(int i=0; i<4; i++) {
if (digits[i] < '0' or digits[i] > '9') {
//throw a fit at the user and return
}
}
printf("thousands: %c, hundreds: %c, tens: %c, ones: %c\n", digits[0].... etc.);