If语句即使不为真也在运行
If statement running even when not true
我不确定我在这里做错了什么,每次我运行它,它通过if
部分,即使它不是真的?所以'else'永远不会运行。
#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"
不是零,所以它是正确的。你也可以这样写(or
= ||
):
if (coice == "F" || true)
与
相同if (true)
所以为了让你的代码工作,你需要:
if (choice == "f" || choice == "F")
if语句语法有问题。以下是更正后的代码,其中'||'代表'或':
if ((choice == "F") || (choice=="f")){
newNo = numb * 0.2 * 9 + 32;
}else{
newNo = (numb - 32) / 1.8;
}
修改if语句
if (choice == "F" or "f"){
到下面的
if (choice == "F" or choice == "f"){
否则为or
的右操作数
"f"
总是等于true,因为它被转换为字符串字面值的第一个字符的地址,该字符显然不等于0。
if语句中的原始条件就像
if (choice == "F" or "f" != nullptr){
和"f" != nullptr
相关文章:
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 为什么我的两个 cin 语句没有在程序结束时运行?
- 如果语句不会在 do - while 循环中运行
- 有没有办法在循环中的条件至少满足一次时运行语句?
- 我的fahrenheit-celcius程序会忽略我的if-else语句,并在每次运行该程序时将值更改为0
- 在后台循环,同时运行其他语句 C++
- c++:if 语句无法正常运行,并继续执行无效输出
- 否则,如果语句无法正常运行
- 在 cout 语句中首先运行什么?(C++17)
- C - 如果语句问题.代码将不会运行其他,否则
- 一个关于在函数中运行未调用语句的非常奇怪的错误
- 如果在不需要的情况下运行语句
- 我可以在开关(消息)语句的同时运行一段时间吗?(C )
- 断言语句无法正常运行
- 如果 2 个数字之间的差值在 1 到 100 之间,则应运行 if 语句
- C 程序运行不正确的其他语句
- 当我做出语句 root->right->right = newnode(7);注释,编译器显示运行时错误。谁能解释为什么?
- 在C程序中,如果在运行时忽略语句
- 使用条件语句在运行时选择不同的模板化矩阵类
- 提示再次运行程序:修复他们是否输入了无效语句