Temperature question

Hey guys, I'm stuck. My code runs fine, but every time I try to input a temperature for one of the else if statements, it kicks back with nothing. I'm trying to write a program where you input an integer as a temperature, and it kicks back saying if its above freezing, freezing, or below freezing.
#include <iostream>

using namespace std;

int main()
{
int a;
cout << "Enter a temperature in celsius!" << endl;
cin >> a;
if (a>1)
{
cout << "This temperature is above the freezing point!" << endl;
}
else if (a=0)
{
cout << "This temperature is the freezing point!" << endl;
}
else if ((a<-1) && (a>-273))
{
cout << "This temperature is below the freezing point!" << endl;
}
return 0;
}
else if (a=0)
= is the assignment operator
== is the equality operator

You are accidentally assigning 0 to a.
fix: else if (a == 0) { ... }

Also, while it may not be realistic, what should happen if the user enters -273, or -274, etc.?
Last edited on
Thanks, this helped a ton! This question was for a test, and while I was forced to enter in the above code, it really bugged me that I couldn't figure it out.
Final Code
#include <iostream>

using namespace std;

int main()
{
int a;
cout << "Enter a temperature in celsius!" << endl;
cin >> a;
if (a>1)
{
cout << "This temperature is above the freezing point!" << endl;
}
else if (a==0)
{
cout << "This temperature is the freezing point!" << endl;
}
else if ((a<-1) && (a>-272))
{
cout << "This temperature is below the freezing point!" << endl;
}
else if (a==-273)
{
cout << "This is absolute zero!" << endl;
}
else if (a<-274)
{
cout << "This is an invalid temperature!" << endl;
}
return 0;
Almost. You are not catching your boundary conditions correctly, though. If you enter 1, -1, -272 or -274, there are no cases that capture these values.

You are using strict greater-than (>) and strict less-than (<). You are really mean to use greater-than-or-equal (>=) and less-than-or-equal (<=)

The value 1 is not > 1, so the first case is not entered.
The value -1 is not < -1, so the third case is not entered.
etc.

After you correct these if statements, you can change the last else if to a simple else because all of the other conditions will have been correctly covered.
After fixing the conditions, every number inputted kicked back both the correct sentence, and the Invalid Temperature sentence. I changed the last else if back from the suggested else to an else if again, and it worked perfectly fine.
Can you post the "fixed" code with the suggested else statement? I'd rather correct your code and explain why you are getting the incorrect output rather than have you stick on the band-aid that disguises the problem.

Please use code tags when you re-post your code. Click the Format button that looks like "<>" and paste your code between the generated tags in the text box.
Topic archived. No new replies allowed.