2016-01-17 65 views
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; 

} 
+0

嘗試打印newNumbers ,newInput,並在循環內輸入結果以查看每次值。 – Bek

+0

而不是檢查輸入是否爲3位數字,也可以使用scanf(「%3d」,&input);這樣做用戶也可以編寫123456,但只有前三個數字將被存儲 –

+0

其實你有一個拒絕小於100的數字的if語句,那麼你如何輸入100作爲輸入。 – phantom

回答

2

在你的代碼,說

if(input > 100) 
     newInput = newNumbers; 
    else if(input > 10) 
     newInput = (newNumbers * 10) + newInput; 

你沒有考慮到的數字10010自己的真實情況,而你也應該數它們。您需要更改if條件使用>=,像

if(input >= 100) 
     newInput = newNumbers; 
    else if(input >= 10) 
     newInput = (newNumbers * 10) + newInput; 
0

嗨一個更簡單的解決方案是僅此一:

output = (input + 666) % 1000; //Add 6 to all numbers 
if(input % 10 > 3)    //Correct units carry 
    output-=10; 
if(input % 100 > 30)   //Correct tents carry 
    output-= 100; 

它的工作原理,易於擴展性:)