Aeron
Aeron

Reputation: 3

Float in if statements returns negative instead given value

Hello I am learning C and I am confused why this certain line returns -126.00 instead of 130.00

here is the source code:

char course1(char course, float price){

    if(course == 'E' || course == 'e') {
        printf("You have taken PHP!\n");
        price = 130.00;
        return price; //returns -126.00
    }
    else
        printf("Invalid!\n");
    return 0;
}
int main() {  
   char course;
   float totalCourse;
   float y = 0;
   scanf(" %c", &course);
   totalCourse += course1(course, y);
   printf("In main, the total is %.2f", totalCourse);

   return 0;
}

When I run the code, and inputs 'E' C returns -126 instead of 130 as given in the source code. Can anyone explain why it happens?

Upvotes: 0

Views: 58

Answers (2)

the busybee
the busybee

Reputation: 12600

The data type char is commonly signed, as it is in your case. A signed char typically has a range from -128 to +127.

You assign the value 130 to such a data type. By the commonly used two's complement, the value 130 is "wrapped around":

  • ...
  • 127 -> +127
  • 128 -> -128
  • 129 -> -127
  • 130 -> -126

Edit:

You can also calculate the resulting value, if you subtract the number of possible values from an input above the range, or add to an input below the range. For the typical char this number is 28 = 256, and you get 130 - 256 = -126.

Use your mathematical skills to bring this in a general formula. ;-)

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

For starters the parameter price is not used within the function. That is its value is ignored.

char course1(char course, float price){

    if(course == 'E' || course == 'e') {
        printf("You have taken PHP!\n");
        price = 130.00;
        return price; //returns -126.00
    }
    else
        printf("Invalid!\n");
    return 0;
}

Secondly the function has the return type char instead of float. It should at least have the return type float.

Apart from this the variable totalCourse was not initialized.

float totalCourse;

So this compound assignment operator +=

totalCourse += course1(course, y);

invokes undefined behavior.

Upvotes: 1

Related Questions