【问题标题】:My simple switch statement doesn't work in C++ [closed]我的简单 switch 语句在 C++ 中不起作用 [关闭]
【发布时间】:2014-09-12 19:40:01
【问题描述】:

我正在尝试编写一个非常简单的 C++ switch 语句,但是尽管从 Absolute C++ 和其他在线示例中阅读了示例代码,但它仍然没有在我想要的时候输出任何东西。为什么这段代码不起作用? (固定)

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <Windows.h>
#include <stdlib.h>
#include <time.h> 
#include <random>

using namespace std;


int main()
{  
int HouseValue;
double AnnualInsuranceCost = 0;
cout << "Enter your total house value estimate: (rounded to nearest 50,000!)\n\n\n";
cin >> HouseValue;

switch (HouseValue)
{
    case 50000:
        AnnualInsuranceCost = 2000;
        break;

    case 100000:
        AnnualInsuranceCost = 3000;
        break;

    case 150000:
        AnnualInsuranceCost = 3500;
        break;

    case 200000:
        AnnualInsuranceCost = 3750; 
        break;

    case 250000:
        AnnualInsuranceCost = 3875;
        break;

}


cout << "\n\n\n\t\t    Your annual insurance cost will be: " << AnnualInsuranceCost << "\n\n\n\t\t\t";



return 0;

}

【问题讨论】:

  • 把最后的cout调用放到switch之外!!!
  • AnnualInsuranceCost == 2,000; --> AnnualInsuranceCost = 2000;
  • 您在case 语句中使用相等运算符,而不是赋值。
  • 您要求他们输入最接近 50,000 的房屋价值。那么为什么要测试值 1、2、3 等呢?您不应该测试50000100000 等吗?
  • 这个问题似乎跑题了,因为它是关于调试作者的第一个 C++ 程序,这是他应该为自己做的。

标签: c++ switch-statement case break


【解决方案1】:

你可以试试这个:

case 5:
        cout << "250000";
        AnnualInsuranceCost = 3875;
        break;
}

cout << "Your annual insurance cost will be: " << AnnualInsuranceCost;
}

否则cout 将成为case 5 的一部分(虽然从未达到。

也改变

AnnualInsuranceCost == 2,000;

AnnualInsuranceCost = 2000;

类似地从您的号码中删除所有comma,== 用于比较,= 用于分配。

【讨论】:

  • @AlexD:- 谢谢。更新:)
  • @PiotrS.:- 是的,更新了。谢谢:)
  • @nwp:- 是的,解决了这个问题。那里有很多要修复的东西。谢谢:)
【解决方案2】:

你期望会发生什么?您提示输入美元数字,例如100,000,并且有 NO case 值会实际匹配。您也没有 default 案例,因此您甚至无法告诉用户没有匹配项。 switch/case 只是编写扩展 if else if else else if else 链的一种奇特方式。

你需要更多类似的东西

switch(HouseValue)
   case 0:  ...
   case 50000: ...
   case 100000: ...
   ...
   default: ... if nothing else matches.

【讨论】:

  • 我不知道案件必须是与之相关的价值。谢谢。
  • switch(foo) { case 'a': ...} 相当于if (foo == 'a')
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 2014-04-12
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多