Search code examples
cintegeroutputfloatingnegative-number

Dividing negative number in C


Hi, i am absolute newbie in programming. I am starting with learning C by book "C Programming Language (2nd Edition)" and stuck in very first example where we get exercise to write simple program that prints values of temperatures from lower to upper in 2 columns (tabs) that contains Celsius a Fahrenheit.

I'v get problem because trying to edit those code for:

  1. Celsius is main system.
  2. Steps measured dynamically by dividing lower on any given number.

And all work perfectly while i am using integers variables.

#include <stdio.h>

main()
{
    int celcius, farenheit;
    int lower, upper, step;

    lower = -273.15;
    upper = 0;
    step = lower / -10; // Dividing lower temperature by given number

    celcius = lower;

    while (celcius <= upper) {
        farenheit = celcius * 9/5 + 32;
        printf("%d\t%d\n", celcius, farenheit);
        celcius = celcius + step;
    }
}

But goes to absolutely random numbers when i try using float or double variables for more precise result: (There is code and output in terminal)

#include <stdio.h>

main()
{
    float celcius, farenheit;
    float lower, upper, step;

    lower = -273.15;
    upper = 0;
    step = lower / -10; // Dividing lower temperature by given number

    celcius = lower;

    while (celcius <= upper) {
        farenheit = celcius * 9/5 + 32;
        printf("%d\t%d\n", celcius, farenheit);
        celcius = celcius + step;
    }
}

Output:

1610612736      1073741824
1073741824      1073741824
-1073741824     1073741824
1073741824      536870912
-1073741824     536870912
1073741824      0
-2147483648     0
-2147483648     -2147483648
536870912       -1610612736
-2147483648     0

So what happened behind that number magic and how to get this to work?


Solution

  • Two problems: first of all, you are doing integer division which causes your quotient to be truncated. Multiply in your calculations by 9./5., not 9/5. The former gives the actual result, but the latter performs integer division

    Your second problem is using %d as your format specifier. You need %f which is for float. Read the man pages for printf for more details.