如果语句运行,即使不正确 [英] If statement running even when not true
本文介绍了如果语句运行,即使不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定我在做什么错,每次运行它时,即使不是真的,它也会通过 if
部分?因此,"else"永远不会运行.
I am not sure what I'm doing wrong here, every time I run it, it goes through the if
part even when it's not true? So the 'else' never runs.
#include <iostream>
using namespace std;
string choice;
float numb;
float convert(float numb,string choice)
{
float newNo;
if (choice == "F" or "f"){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
return newNo;
}
int main()
{
cout << "welcome to Temperature converter v0.1" << endl;
cout << endl;
cout << "Which conversion would you like to use?" << endl;
cout << "type C to convert to Celsius and F to convert to Fahrenheit - ";
cin >> choice;
cout << "what number would you like to convert? - ";
cin >> numb;
cout << convert(numb,choice);
return 0;
}
推荐答案
问题出在您的 if
语句:
if (choice == "F" or "f"){
基本上,您在这里说的是:如果选择是"F"或"f".您需要了解:除零( 0
)之外的所有内容都是真实的."f"
不为零,因此为true.您也可以输入( or
= ||
):
basically, what you say here is:
If choise is "F" or if "f". You need to understand: True is everything besides zero (0
). "f"
is NOT zero, so it is true. You could also wirte (or
= ||
):
if (coice == "F" || true)
类似于:
if (true)
因此,为了使您的代码正常工作,您需要:
So in order for your code to work, you need:
if (choice == "f" || choice == "F")
那可以满足您的期望.
这篇关于如果语句运行,即使不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文