我撰寫了一個程式來接受 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;
}
該怎么辦?
uj5u.com熱心網友回復:
你可以試試下面的代碼
if(a<1000 || a>9999)
{
printf("Only 4-digits are allowed:");
}
uj5u.com熱心網友回復:
這取決于“0999”是否被視為 4 位數字。如果不是,那么任何已經發布的解決方案都將起作用。如果是,則必須將輸入掃描為字串,以便在將其轉換為 int 之前測驗其長度。你也可以走這條路:
char digits[5];
scanf("%c%c%c%c", &digits[0], &digits[1], &digits[2], &digits[3]);
digits[4] = '\0'; // 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.);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316332.html
上一篇:改變WCF信封請求的前綴命名空間
下一篇:C中字符的條件
