1
我正在寫一個程序,通過6的10的if..else的if..else循環未正確執行
模量例如,如果要求用戶輸入然後一個三位數將每個數我輸入619,我將收到的輸出是275.
我唯一的問題是當我輸入100,我收到1360,而不是像我應該的766。
這是我到目前爲止有:
int main()
{
//declaring variables
int numbers, newNumbers, input;
int newInput = 0;
//User input
printf("Enter a three-digit number: ");
//reads input (%d) and stores it as "input" (&input)
scanf("%d", &input);
//check if input is 3 digits. If not, print message
if(input < 100 || input > 999)
{
printf("Invalid input, the number must be between 100 and 999 \n");
return 0;
}
//loops program until input is 0
while(input > 0)
{
//modulus 10
numbers = input % 10;
//adds 6 to input. Modulus 10
newNumbers = (numbers + 6) % 10;
//if input > 10, calculates new input
if(input > 100)
newInput = newNumbers;
else if(input > 10)
newInput = (newNumbers * 10) + newInput;
else
newInput = (newNumbers * 100) + newInput;
input /= 10;
}
//prints result
printf("Output: %d \n", newInput);
return 0;
}
嘗試打印newNumbers ,newInput,並在循環內輸入結果以查看每次值。 – Bek
而不是檢查輸入是否爲3位數字,也可以使用scanf(「%3d」,&input);這樣做用戶也可以編寫123456,但只有前三個數字將被存儲 –
其實你有一個拒絕小於100的數字的if語句,那麼你如何輸入100作爲輸入。 – phantom