0

I have a simple calculator in c++ but I also want to add % operation for decimal division. I want to add 5 functions, addition, division, multiplication, subtraction. Everything works but decimal division no. I've got error when I trying to compile. Here is my code:

# include <iostream>
# include <cmath>
# include <cstdio>
using namespace std;

int main()
{
    char operation;
    float number1, number2;
    float fmod;
    cout << "Enter operation +, -, *, / : ";
    cin >> operation;

    cout << "Enter two numbers: ";
    cin >> number1 >> number2;
    

    switch(operation)
    {
        case '+':
            cout << number1+number2;
            break;

        case '-':
            cout << number1-number2;
            break;

        case '*':
            cout << number1*number2;
            break;

        case '/':
            cout << number1/number2;
            break;
        
        case '%':
            cout << number1%number2;
            break;
            
        default:
            cout << "err";
            break;
    }
    return 0;
    
}

Can anyone explain how I can add this function?

Bazejoo
  • 37
  • 1
  • 1
  • 8

1 Answers1

1

The modulo operator cannot be used with float numbers. You can do this instead :

case '%':
    cout << fmodf(number1, number2);
    break;

Note however that it is not usual to use a modulo with float numbers on a calculator. So another thing you could do would be to round and cast the numbers :

case '%':
    cout << (int)roundf(number1) % (int)roundf(number2);
    break;
dspr
  • 2,383
  • 2
  • 15
  • 19