简体   繁体   中英

I am having trouble implementing a “while loop” in C programming

For my class, I had to create a Calculator. In this code that I wrote, I tried to implement the "while loop" so that the program would run continuously and I also wanted it to end when the user typed in XO which is short for exit operation. I kept getting errors on my IDE when I tried to run the program. Can anyone help me figure the rest of this out or help me find the resources to figure this out. Thanks

very respectfully,

#include <stdio.h>
#include <stdlib.h>

int main()

{
    char letter;
    float num1,num2;
    printf("What operation do you want to do\n\tA)Addition\n\tB)Subtraction 
    \n\tC)Multiplication\n\tD)Division\n?");
    scanf("%c" ,&letter);
    printf("Please enter a number :");
    scanf("%f" ,&num1);
    printf("Please enter another number :");
    scanf("%f" ,&num2);
    if (letter=='A' || letter=='a')
        printf("The sum of %.2f and %.2f is %.2f" ,num1,num2,num1+num2);
    else if (letter=='B' || letter=='b')
        printf("The difference of %.2f and %.2f is %.2f" ,num1,num2,num1-  
        num2);
    else if (letter=='C' || letter=='c')
        printf("The product of %.2f and %.2f is %.2f ,num1,num2,num1*num2");
    else if(letter=='D' || letter=='d')
        printf("The quotient of %.2f and %.2f is %.2f 
        ,num1,num2,num1/num2");
    else
        printf("You entered an invalid character.");

    return 0;
}

I'll give you a little help here, though you still have some work left to get this working.

A while loop that will run indefinitely is made like this:

while(1) {
    //Your code here
}

If you want to stop that loop when the user enters X , try this:

while(1) {
    scanf("%c" ,&letter);
    if(letter == 'X') {
        printf("Goodbye!");
        break;
    }
}

Hopefully that points you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM