创建一个程序,要求用户输入两个数字,并有三个可能的答案.代码未编译.数字(作为int)
Creating a program that asks the user for two numbers and has three possible answers. code not compiling. number(as an int)
所以我最近开始使用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
相关文章:
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 整数区间(或 int 数组)中每个数字的出现次数
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 无符号的 int 到有效数字
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- C++ - 将 int 读取为字母和数字序列
- 如何安全地将有符号字段从uint32_t提取到有符号数字(int或uint32_t)中
- 如果char可以在C++中存储数字,为什么我们需要int
- 检查字符串是否是数字,然后将该数字转换为 int?
- C++在减去 int 时向 int 添加一个额外的数字
- 如何使用 c++ 中的 int* count(const string&s)计算字符串中每个数字的出现次数?
- 当我将 const int 声明/初始化为 5 时,它被初始化为一个大数字
- 如何将int分解为数字并以相同的顺序为向量分配数字
- 从C 到C#调用INT []显示随机大数字,而不是原始数组成员
- 如何将 int 的数字分配给数组 c++
- 如何正确编码此函数,以便它计算 int 的每个数字的总和
- C++ 从文件中读取 int,每个数字用逗号分隔
- 为什么将字符'g'读入 int 会产生此代码中的数字 -858993460?
- 如何将强调字符转换为数字(INT)CPP
- 如何从char数组中读取数字(int)值