[try Beta version]
Not logged in

 
If statements, multiple choices

May 6, 2018 at 4:59am
When I run the following code I get the error "Code will never be executed" at the beginning of the second 'if' statement. How do I fix this?

#include <iostream>
using namespace std;

int main() {
float Celsius, Fahrenheit;
char choice;
char c, f, C, F;

cout << "Enter c (or C) to convert Fahrenheit to Celsius or f (or F) to convert Celsius to Fahrenheit: \n";
cin >> choice;

if (choice == 'c' || 'C') {
cout << "Enter the temperature in Celsius : ";
cin >> Celsius;
Fahrenheit = (Celsius * 9.0) / 5.0 + 32;
cout << "The temperature in Fahrenheit: " << Fahrenheit << endl;
return (0);
}

if (choice == 'f' || 'F') {
cout << "Enter the temperature in Fahrenheit: ";
cin >> Fahrenheit;
Celsius = (Fahrenheit - 32) * 5/9;
cout << "The temperature in Celsius: " << Celsius << endl;
return (0);
}

return (0);
}
May 6, 2018 at 5:20am
You have return 0; after every statement, but you only need return 0; once at the end of your main
May 6, 2018 at 5:27am
Thank you. I removed those statements but when I run it and input "f" or "F" the output still reads "Enter the temperature in Celsius:" and then it converts celsius to Fahrenheit. Why isn't it doing Fahrenheit to celsius when I choose "f" or "F"?
May 6, 2018 at 8:17am
if (choice == 'f' || 'F') {
This doesn't mean what you think it means. This is always true, because you're not comparing 'F' to anything. You're just saying 'F', which evaluates to true. You've got
if (choice == 'f' || true ) {
which always comes out as true.


Likewise if (choice == 'c' || 'C') is if (choice == 'c' || true ) {
Last edited on May 6, 2018 at 8:18am
Topic archived. No new replies allowed.