0

I have made a simple calculator.

I have 4 functions, addition, subtraction, multiply and division. They are called in another function called "User()" with a switch case statement.

In order to keep the program running after the user has performed one calculation i have added a while loop. When you complete the first iteration of the loop, it runs the User() function twice. Does anyone know why the function is called twice?

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

double addition();
double subtraction();
double multiply();
void User();

int main()
{

    while(1)
    {
        User();
        printf("\n\n\n");
    }


    return 0;
}

double addition()
{
    double num1, num2;
    printf("Please enter two numbers to add\n");
    scanf("%lf %lf", &num1, &num2);
    double sum = num1+num2;
    printf("The results are: %lf + %lf = %lf", num1, num2, sum);
}


double subtraction()
{
    double num1, num2;
    printf("Please enter two numbers to subtract\n");
    scanf("%lf %lf", &num1, &num2);
    double sum = num1-num2;
    printf("The results are: %lf - %lf = %lf", num1, num2, sum);
}

double multiply()
{
    double num1, num2;
    printf("Please enter two numbers you wish to multiply\n");
    scanf("%lf %lf", &num1, &num2);
    double sum = num1*num2;
    printf("The results are: %lf * %lf = %lf", num1, num2, sum);
}

double division()
{
    double num1, num2;
    printf("Please enter two numbers you wish to divide\n");
    scanf("lf %lf", &num1,&num2);
    double sum = num1/num2;
    printf("The results are: %lf / %lf = %lf", num1, num2, sum);
}
void User()
{
    char Operator;
    printf("Please enter which calculation you would like to perform:\nAddition: +\nSubtraction: -\nMultiply: *\nDivide: /\n");
    scanf("%c", &Operator);

    
    switch(Operator)
    {
    case('+'):
        addition();
        break;
    case('-'):
        subtraction();
        break;
    case('/'):
        division();
        break;
    case('*'):
        multiply();
        break;
    }
}

This is the output of the console: Output after one interation

noobi3
  • 40
  • 8
  • 1
    Here you go: the first thing to look for is any `%c` or `%[]` format such as `scanf("%c", &Operator);` which will read the previous newline left in the input. Try `scanf(" %c", &Operator);` with that space to filter the newline. Please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Jan 02 '22 at 17:53
  • 1
    You might get a better idea if you put a `default:` case in your `switch`. – Barmar Jan 02 '22 at 17:53
  • Wow... Thanks a lot @WeatherVane! That worked perfectly. One less mistake ill make in the future! – noobi3 Jan 02 '22 at 18:01
  • 1
    Welcome. Don't forget that it's asymptotic.... – Weather Vane Jan 02 '22 at 18:03

0 Answers0