Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"conversion to 'float' from 'int' may alter its value"

I researched the error and haven’t been able to find it. Also I am new to this. I want to learn the basics of C and here is my first program. I want to modify sum in the function calc so it is a float in case someone divides for example 2/5.

#include <stdio.h>

int getNumber1() {
    int myNumber1;
    printf("\n gib eine Zahl ein: ");
    scanf("%d", &myNumber1);
    return myNumber1;
}

int getNumber2() {
    int myNumber2;
    printf("\n gib eine weitere Zahl ein: ");
    scanf("%d", &myNumber2);
    return myNumber2;
}

char getOp() {
    char myOp;
    printf("\n gib einen Operanten ein: ");
    scanf(" %c", &myOp);
    return myOp;
}

void calc(int number1, int number2, char op) {
    if (op == '+') {
        int sum = number1 + number2;
        printf("\n\n%d %c %d = %d", number1, op, number2, sum);
    }
    if (op == '-') {
        int sum = number1 - number2;
        printf("\n\n%d %c %d = %d", number1, op, number2, sum);
    }
    if (op == '*') {
        int sum = number1 * number2;
        printf("\n\n%d %c %d = %d", number1, op, number2, sum);
    }
    if (op == '/') {
        float sum = number1 / number2;
        printf("\n\n%d %c %d = %.2f", number1, op, number2, sum);
    }
}

int main() {
    int cont = 1;
    while (cont == 1) {
        int number1 = getNumber1();
        int number2 = getNumber2();
        char op = getOp();
        calc(number1, number2, op);
        printf("\nMoechten Sie weitere Berechnungen durchfuehren? (1 fuer Ja, 0 fuer Nein): ");
        scanf("%d", &cont);
    }
    printf("\nDanke und auf Wiedersehen.");
    return 0;
}

But I get the error that conversion to float from int may alter its value. Why is that and how can I solve the error?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The compiler issues the message because an integer value is assigned to a variable of the floating type float.

In this statement

float sum = number1 / number2;

the expression number1 / number2 is evaluated using the integer arithmetic. So assigning to a variable of the type float does not make a great sense.

Instead write for exameple

float sum = ( float )number1 / number2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading