Fahrenheit to Celcius

Sep 26, 2011 at 11:27pm
#include<iostream>
#include<iomanip>

using namespace std;

int main()

{
float tempF;
float tempC;

cout << "Please input the temperature in celcius" <<endl;
cin >> tempC;

cout << setprecision(2) << fixed;
tempF = (9/5)(tempC) + 32;
cout << "The temperature in Fahrenheit is " << tempF <<endl;


return 0;

}



PROBLEMS??
Sep 26, 2011 at 11:31pm
closed account (EvoTURfi)
Use * for this line instead of using ()():

tempF = (9/5)(tempC) + 32;

Like this:

tempF = ((9/5)*(tempC)) + 32;

Other than that, I don't see any problems.
Last edited on Sep 26, 2011 at 11:32pm
Sep 26, 2011 at 11:33pm
YES

2 problems that I see. (In fact I knew what one of them was just from the title! Such a common problem)

 
tempF = (9/5)(tempC) + 32;


The two problems are:

1) C++ is not algebra. Parenthesis do not imply multiplication. If you want to multiply something, you NEED to use the * operator:

1
2
(x)(y) // bad
(x)*(y)  // good 


2) If you divide 2 integers in C++, the result will be an integer. This means that (9/5) results in the integer 1 and not 1.8 like you might expect.

To get around this, do floating point division: (9.0f / 5.0f)
Sep 27, 2011 at 12:28am
closed account (EvoTURfi)
@Disch: Or you could just take in the operation into a float variable.
Sep 27, 2011 at 1:17am
Or you could do the multiplication first

(9 * tempC / 5) + 32;

There are multiple ways to fix it ;P
Sep 27, 2011 at 7:12pm
Thank you all very much. very helpful @disch does float tempF; float tempC; not already make them floating points?
Sep 27, 2011 at 7:24pm
No, because tempF and tempC are not involved in the expression.

The compiler does things one step at a time. In complex expressions like this, it breaks it down and does each step on its own. While it's doing one step, it is totally oblivious to the other steps.

So let's take a look at this again:

tempF = (9/5)*(tempC) + 32;

The intent seems obvious to us humans, but the compiler sees it differently. It does this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// okay, first expression I need to evaluate:
(9/5)

// these are 2 integers, so do integer division.  result is 1
(1)

// next in the expression:
(1) * (tempC)

// 1 is an int and tempC is a float, so the result will be a float
//  1 * tempC is tempC:
tempC

// next in the expression:
tempC + 32

// ... etc 



That said... if you involve tempC in the expression, it will promote it to a float.

For example... all of these will work fine because tempC makes the expression a float immediately:

1
2
3
4
5
tempF = (tempC * 9 / 5) + 32;

tempF = (tempC / 5 * 9) + 32;

tempF = (9 * tempC / 5) + 32;
Last edited on Sep 27, 2011 at 7:26pm
Topic archived. No new replies allowed.