C++ Illegal else
C++ Illegal else
好吧,我想制作一个简单的IPO循环,要求Wahrenheit或Celsius转换,然后根据他们的选择转换用户输入。我想我已经知道了,但是我的其他条款弄乱了。我无法弄清楚,在看了很长时间之后,也许新鲜的眼睛可以更轻松地指出我的错误?
代码:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int _tmain()
{
int choice;
double fahr, cel;
cout << "Please choose 1 for fahrenheit, or 2 for Celsius: ";
if (cin >> choice) {
while (cin >> choice){
if (choice == 1)
cout << "Enter Fahrenheit degrees to be converted: " << endl;
cin >> fahr;
cel = (fahr - 32.0) / 1.8;
cout << cel << " degrees" << endl;
if(choice == 2)
cout << "Enter Celsius degrees to be converted: " << endl;
cin >> cel;
fahr = 9.0 / 5.0 * cel + 32.0;
cout << fahr << " degrees" << endl;
else {
cout << "Not a valid option";
}
}
}
return 0;
}
在需要定义代码范围时添加括号{}
。
这样:
if (choice == 1)
{
cout << "Enter Fahrenheit degrees to be converted: " << endl;
cin >> fahr;
cel = (fahr - 32.0) / 1.8;
cout << cel << " degrees" << endl;
}
if(choice == 2)
{
cout << "Enter Celsius degrees to be converted: " << endl;
cin >> cel;
fahr = 9.0 / 5.0 * cel + 32.0;
cout << fahr << " degrees" << endl;
}
else
{
cout << "Not a valid option";
}
您没有在您的IF周围放卷曲牙套:
if (choice == 1){
cout << "Enter Fahrenheit degrees to be converted: " << endl;
cin >> fahr;
cel = (fahr - 32.0) / 1.8;
cout << cel << " degrees" << endl;
}
else if(choice == 2){
cout << "Enter Celsius degrees to be converted: " << endl;
cin >> cel;
fahr = 9.0 / 5.0 * cel + 32.0;
cout << fahr << " degrees" << endl;
}
else {
cout << "Not a valid option";
}
我认为您需要做2件事:1.使用支架支架包围所有条件应执行的所有语句。这将阐明该语句的范围。2.如果使用其他情况,则更改第二个,假设您希望用户输入选项1或2,但不能同时使用。
您错过了两个if
s中的括号。当遇到if
时,它仅执行cout
语句。如果您希望它执行多个语句,则应添加卷曲括号{}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- c++ std::enable_if .... else?
- 如果 else 语句不断循环
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 为什么我的最后一个 ELSE 条件无法正确执行
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 如果 else 语句使用大写和小写字母
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- C++ Illegal else