Problem using constants in calculations..

Hey all, this is my first post on cplusplus.com:

I am fairly new to C++, and am having trouble trying to convert temperatures
while using constants in the equations (for an assignment).

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"

double f_temp, c_temp, k_temp;			

double Temperatures(double f_temp) {
	const  double c1 = 5 / 9;			
	const  double c2 = 32;
	const  double c3 = 273.16;

	c_temp = (c1 * f_temp) + c2;		/*Converting Fahrenheit to 
                                                      Celsius.*/
	
	k_temp = (c_temp + c3);				/*Converting Celsius to 
                                                             Kelvin.*/
	

	printf("The original temperature is %.2f degrees Fahrenheit. \n\n ", f_temp);	
	printf("This temperature in Celsius is %.2f degrees Celsius. \n\n ", c_temp);
	printf("This temperature in Kelvin is %.2f Kelvin. \n\n ", k_temp);

	return 0;
}


When I run the program, the fahrenheit input is correct but the other two conversions are coming up wrong, any help or insight is appreciated!
Last edited on
Here: const double c1 = 5 / 9;

Even though c1 is a double, both 5 and 9 are integers.
integer division discards the fractional part, so 5 / 9 is equivalent to 0.

To fix it, use literal doubles instead of literal integers:
const double c1 = 5.0 / 9.0;
Last edited on
Thanks for the quick response! You also made me realize my fahrenheit to celsius formula was wrong.. haha.

Cheers m8!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// double f_temp, c_temp, k_temp; // we don't need these globals

// return void if we don't have anything meaningful to return
void print_temperatures( double f_temp ) {

    // static: these constants can be reused over and over again
    // (just good style; in practice, doesn't make a difference because the compiler knows it too.)
    // perhaps, give somewhat more meaningful names for this constants.
    static const  double c1 = 5 / 9.0 ;
    static const  double c2 = 32;
    static const  double c3 = 273.16; // should be 273.15 iirc

    // in contrast, the constants c_temp and k_temp are not static
    // they are freshly recomputed each time the function is called
    const double c_temp = (f_temp-c2) * c1;
    const double k_temp = c_temp + c3 ;

    if( k_temp >= 0 ) // sanity check: not below absolute zero
                      // https://en.wikipedia.org/wiki/Absolute_zero
    {
        printf("The original temperature is %.2f degrees Fahrenheit. \n\n ", f_temp);
        printf("This temperature in Celsius is %.2f degrees Celsius. \n\n ", c_temp);
        printf("This temperature in Kelvin is %.2f Kelvin. \n\n ", k_temp);
    }

    else printf( "invalid temperature: %.2f degrees Fahrenheit is below absolute zero.\n\n ", f_temp );
}
Topic archived. No new replies allowed.