创建一个程序,要求用户输入两个数字,并有三个可能的答案.代码未编译.数字(作为int)

Creating a program that asks the user for two numbers and has three possible answers. code not compiling. number(as an int)

本文关键字:数字 int 三个 答案 编译 代码 作为 两个 程序 一个 用户      更新时间:2023-10-16

所以我最近开始使用C++,其中一个挑战是创建一个要求两个数字的程序,它必须说if;其中一个数字是正的,两个都是正的或者两个都不是正的。我试着在没有if的情况下制作一个开关结构,但似乎没有成功。这是我的密码。

#include <iostream>
using namespace std;
int main()
{
int number;
int number2;
cout <<"Introduce two numbers:" ;
cin >> number, number2;
switch(number)
{
case (number > 0) (number2 > 0): cout <<"Both numbers are positive.";
break;
case (number > 0) (number2 < 0): cout <<"One of the numbers is positive.";
break;
case (number < 0) (number2 > 0): cout <<"One of the numbers is positive.";
break;
case (number < 0) (number2 < 0): cout <<"None of the numbers are positive.";
break;
default: cout <<"It must be a number.";
}
return 0;
}

我得到的编译错误如下。在函数"int main()"中:

[错误]"number"不能出现在常量表达式中

[错误]"number2"不能出现在常量表达式中

[Error]函数调用不能出现在常量表达式中

[错误]"number"不能出现在常量表达式中

[错误]"number2"不能出现在常量表达式中

[Error]函数调用不能出现在常量表达式中

[错误]"number"不能出现在常量表达式中

[错误]"number2"不能出现在常量表达式中

[Error]函数调用不能出现在常量表达式中

[错误]"number"不能出现在常量表达式中

[错误]"number2"不能出现在常量表达式中

[Error]函数调用不能出现在常量表达式中

您遇到的问题是switch语句中的事例只能取常量。

例如,这是有效的:

switch (number)
{
case 0:
// Do something because number is 0
break;
case 1:
// Do something because number is 1
break;
case -5:
break;
//etc...
}

基本上,不能在case关键字之后使用变量。因此,您需要使用if来执行您想要的操作,而使用switch是不可能的。

关于switch语句的更多阅读:http://www.tutorialspoint.com/cplusplus/cpp_switch_statement.htm