0

So I tried to program a little calculator in C to do addition, subtraction , multiplication , division and modulus everything works perfectly except the modulus operator and I don't know why so here is my code and modulus is inside case 5 in the switch statement :

#include <stdio.h>

void main(){

    float n1=0.0;
    float n2=0.0;
    float n3=0.0;
    int choix=0;
        printf("\nRentrer le Premier Chiffre:");
        scanf("%f" , &n1);
        
        printf("\nRentrer le Deuxieme Chiffre:");
        scanf("%f" , &n2);

    printf("\n\tEcrire 1 pour une addition\n\tEcrire 2 pour une soustraction\n\tEcrire 3 pour une multiplication\n\tEcrire 4 pour une division\n\tEcrire 5 pour modulus:");
    scanf("%d" , &choix);

    switch (choix)
    {
        case 1: 
        n3=n1+n2;
        printf("L'addition de %.2f+%.2f=%.2f" , n1 , n2, n3);
        break;

        case 2: 
        n3=n1-n2;
        printf("La soustraction %.2f-%.2f=%.2f" , n1 , n2, n3);
        break;

        case 3:
        n3=n1*n2;
        printf("La multiplication %.2f*%.2f=%.2f" , n1 , n2, n3);
        break;

        case 4:
        n3=n1/n2;
        printf("La division %.2f/%.2f=%.2f" , n1 , n2, n3);
        break;

        case 5:
        n3=n1%n2;
        printf("Le modulus de %.2f et %.2f=%.2f" , n1 , n2, n3);
        break;

        default: 
        printf("Entrer un choix valide!");
        break;

    }

}

It give me this error :

In function 'main':
calculatrice.c:41:8: error: invalid operands to binary % (have 'float' and 'float')
   n3=n1%n2;
    ^

So if someone could help me or lead me where the problem is it would be gladly appreciated :)

Mister-3
  • 27
  • 6
  • 3
    Use [`fmod()`](https://en.cppreference.com/w/c/numeric/math/fmod) for floating point. – 001 Nov 16 '21 at 21:13
  • @Mister-3 The operator % is not defined for floating point numbers. – Vlad from Moscow Nov 16 '21 at 21:13
  • Possibly what you searched for is [this](https://stackoverflow.com/questions/6102948/why-does-modulus-division-only-work-with-integers) – JANO Nov 16 '21 at 21:15
  • Perfect guys thanks did not knew about the math.h library , I included it and modified the case 5 as this : case 5: n3=fmod(n1,n2); printf("Le modulus de %.2f et %.2f=%.2f" , n1 , n2, n3); break; – Mister-3 Nov 16 '21 at 21:19
  • For `float, float`, use `fmodf()` (note suffix `f`). – chux - Reinstate Monica Nov 16 '21 at 21:38
  • Note: `%` and `fmod()` are better described as a _remainder_, rather than _modulo_. Results differ when the first operand is [negative](https://stackoverflow.com/a/20638659/2410359). – chux - Reinstate Monica Nov 16 '21 at 22:33

0 Answers0