2017-10-16 61 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 
}