2017-10-16 67 views
0

晚上好,y/n循環結束功能

這是我的代碼。我正在製作一個小型計算器,但是我最終還是在努力以y/n循環重複該函數。我看過別人,但似乎無法得到正確的答案。 謝謝。

#include <stdio.h> 

int main() 
{ 
    int n, num1, num2, result; 
    char answer; 
    { 
    printf("\nWhat operation do you want to perform?\n"); 
    printf("Press 1 for addition.\n"); 
    printf("Press 2 for subtraction.\n"); 
    printf("Press 3 for multiplication.\n"); 
    printf("Press 4 for division.\n"); 
    scanf("%d", &n); 
    printf("Please enter a number.\n"); 
    scanf("%d", &num1); 
    printf("Please enter the second number.\n"); 
    scanf("%d", &num2); 
    switch(n) 
    { 
     case 1: result = num1 + num2; 
       printf("The addition of the two numbers is %d\n", result); 
       break; 
     case 2: result = num1 - num2; 
       printf("The subtraction of the two numbers is %d\n", result); 
       break; 
     case 3: result = num1 * num2; 
       printf("The multiplication of the two numbers is %d\n", result); 
       break; 
     case 4: result = num1/num2; 
       printf("The division of the two numbers is %d\n", result); 
       break; 
     default: printf("Wrong input!!!"); 
    } 
    printf("\nDo you want to continue, y/n?\n"); 
    scanf("%c", &answer); 
    while(answer == 'y'); 

    } 
    return 0; 
} 
+0

您正在使用錯誤while循環。請看一些示例,然後你可以正確地做到這一點。 – Talal

+0

將所有東西包裝在後測循環中。 –

+1

我想你想要一個['do/while'](https://www.tutorialspoint.com/cprogramming/c_do_while_loop.htm)循環。 –

回答

3

你有這樣的代碼

char answer; 
    { 
    printf("\nWhat operation do you want to perform?\n"); 
    //... 
    //... more code 
    //... 
    printf("\nDo you want to continue, y/n?\n"); 
    scanf("%c", &answer); 
    while(answer == 'y'); 

    } 

嘗試將其更改爲:

char answer; 
    do { 
    printf("\nWhat operation do you want to perform?\n"); 
    //... 
    //... more code 
    //... 
    printf("\nDo you want to continue, y/n?\n"); 
    scanf("%c", &answer); 
    } while(answer == 'y'); 

所以基本形式是:

do { 
    // code to repeat 
} while (Boolean-expression); 

順便說一句 - 你應該經常檢查由返回的值10

實施例:

if (scanf("%c", &answer) != 1) 
{ 
    // Add error handling 
} 

還要注意,常常希望%c之前的空間在輸入流中除去任何空白空間(包括新行)。像

if (scanf(" %c", &answer) != 1) 
{ 
    // Add error handling 
}