【问题标题】:trying to create a switch with logical operators尝试使用逻辑运算符创建开关
【发布时间】:2026-02-16 06:25:02
【问题描述】:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int Hours;
    cout << "please enter number of hours worked";
    cin >> Hours;
    switch (Hours)
    {
    case 1: Hours == 40;
        cout << "worked full time this week";
        break;
    case 2:   Hours <= 30;
        cout << "You worked less than 40 this week available shifts on board";
        break;
    case 3: Hours > 30 && Hours < 40;
        cout << "You almost have 40 hrs check the board to see if shifts are available please do not go over 40 hrs";
        break;
    default: 
        cout << " invalid entry see you manager or try again";
    }



    {



    return 0;

}

老实说,我做错了什么,我并不真正理解 switch 语句,所以只是做一些非常基本的事情。每次尝试运行它时都会出现构建错误。我希望用户输入工作了多少小时并基于该显示消息。老实说,我认为 if/else 语句会更好,但我想使用 switch 语句来进行一些练习。

【问题讨论】:

标签: c++ switch-statement


【解决方案1】:

这不是你使用switch的方式

switch 将获取该值并将其与所有case 进行比较。使用switch 不能做大做小。

你应该改用if-else

if(Hours == 40)
{
    std::cout << "worked full time this week";
}
else if(Hours <= 30)
{
    std::cout << "You worked less than 40 this week available shifts on board";
}
else if(Hours > 30 && Hours < 40)
{
    std::cout << "You almost have 40 hrs check the board to see if shifts are available please do not go over 40 hrs";
}
else
{
    std::cout << " invalid entry see you manager or try again";
} 

【讨论】: