Stuck in an infinite loop

I'm trying to make a program that can convert Celsius to Fahrenheit and vice versa. I thing I have made it right, but when I try to run the code it enters into an infinite loop, even after I take out the while statement. Any idea why that's happening?


#include<iostream>

using namespace std;

float degree;
double C;
double F;
double Q;
double newC = (F - 32) / 1.8;
double newF = (1.8 * C) + 32;

int main()
{
while (degree != Q) {
cout << "Enter C to convert Fehrenheit to Celcius, and F to do the oppisite. Enter Q to quit." << endl;
cin >> degree;

if (degree != Q) {
cout << "Enter value you want to be converted." << endl;
cin >> degree << endl;

if (degree = C) {
cout << newC;
}
else {
cout << newF;
}
}
}
return 0;
}
closed account (48T7M4Gy)
Your problem is degree is a double and ‘Q’ is a char so the while condition will always be true, so off to infinity.
This looks sensible,
 
while (degree != Q) {
until we examine it more closely.

We would expect two characters to be compared, type char. But degree is a float and Q is a double.

I'd change it to something like this:
1
2
3
    char mode = ' ';
    
    while (mode != 'q') {


Now mode is a character variable and 'q' is a character literal. You will need to change the code so that it properly uses cin >> mode where needed and also change the comparison if (degree = C) to if (mode == 'c')

Note in that last example that == is used to test for equality. A single = is the assignment operator, something very different.
Last edited on
Topic archived. No new replies allowed.