Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"while()" function?

Tags:

c

while-loop

This program is supposed to convert degrees Fahrenheit into degrees Celsius:

#include <stdio.h>
int main() {
    float fahrenheit, celsius;
    int max, min, step;

    max = 100;
    min = 0;
    step = 5;

    fahrenheit = 0.0;
    //celsius = (fahrenheit - 32.0) * 5.0/9.0; DOESN'T WORK HERE

    printf("\n");
    printf("This program converts fahrenheit into celsius \n");

    while(fahrenheit <= max) {
        celsius = (fahrenheit - 32.0) * 5.0/9.0; /* Works here */
        printf("%3.0f %6.2f\n", fahrenheit, celsius);
        fahrenheit = fahrenheit + step;
    }
}

As I noted in my source comments, when I try put the formula for celsius into the body of the main() function, I get -17.8 for every single fahrenheit value. The output looks like this -

0 -17.78
5 -17.78
10 -17.78
15 -17.78
20 -17.78
25 -17.78

and so on and so on. However, when I put the celsius formula into the while() function, I get the correct celsius values for each fahrenheit value. It looks like this:

0 -17.78
5 -15.00
10 -12.22
15  -9.44
20  -6.67

Why does that happen?

Here's the code that doesn't work. It's identical to the code above, except for the location of the celsius formula. (At least, I think it is.)

#include <stdio.h>
//this program is supposed to convert fahrenheit into celsius 
int main() {
    float fahrenheit, celsius;
    int max, min, step;

    max = 100;
    min = 0;
    step = 5;

    fahrenheit = 0.0;
    celsius = (fahrenheit - 32.0) * 5.0/9.0; 

    printf("\n");
    printf("This program converts fahrenheit into celsius \n");

    while(fahrenheit <= max) {
        printf("%3.0f %6.2f\n", fahrenheit, celsius);
        fahrenheit = fahrenheit + step;
    }
}
like image 950
Steve3043 Avatar asked Dec 13 '14 00:12

Steve3043


1 Answers

When you set a value to a variable, the actual value is computed, and then stored to the variable. You do not store a formula for the variable, however. Thus, when you run

celsius = (fahrenheit - 32.0) * 5.0/9.0;

outside of the while loop, it uses the current value of fahrenheit (which is 0.0), and calculates the value for celsius, which is -17.78.

Inside the while loop, although fahrenheit changes, celsius will not, because there are no statements inside of the while loop to actually change the value of the variable. This is why you have to move the statement into the while loop, to make sure that the celsius value updates every time the fahrenheit value changes.

like image 91
kevinji Avatar answered Oct 15 '22 04:10

kevinji