gpt4 book ai didi

c++ - Switch 语句输出错误的成本值

转载 作者:行者123 更新时间:2023-11-28 02:40:49 24 4
gpt4 key购买 nike

当我尝试在 Microsoft Visual Studio C++ 上运行此代码时;它运行但输出的成本值是错误的。这是为什么?我确实意识到我没有包括默认声明,并且我正在声明 cost两次,这是因为我收到 cost 的调试错误没有声明的值,所以我假设正在发生的是 switch 语句没有处理,因为它有些不理解
cout << "Pizza";我该如何解决这个问题?

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

using namespace std;

int main()
{
int a, b, c, d, e, f, m, p, k, User_Input, Pizza , cost;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
k = 0;
cost = 0;

cout << "What is your favorite vegetarian food from the list below?" << endl;
Sleep(1500);
cout << "Pizza\n";
Sleep(200);
cout << "IceCream\n";

cin >> User_Input;
switch (User_Input)
{
case 1:
cout << "Pizza";
cost = 5;
break;
case 2:
cout << "IceCream";
cost = 5;
break;

}


Sleep(2000);
cout << "The total cost will be: " << cost;
cout << "\n\n\n\t\t\t";

return 0;


}

最佳答案

User_Input 是“int”类型,如果您尝试通过 cin 将字符串读取到该变量,您将得到意想不到的结果。您可能想要做的是:

  • 读入一个字符串并进行字符串比较
  • 读入字符串,转int,执行switch语句

一个简化的例子:

#include <iostream>
#include <string>
int main()
{
std::string user_input;
int cost = 0;
std::cout << "What is your favorite vegetarian food from the list below?\nPizza\nIceCream\n";
std::cin >> user_input;
if(user_input == "Pizza") {
cost = 5;
} else if (user_input == "IceCream") {
cost = 10;
}
std::cout << "The total cost will be: " << cost << std::endl;
return 0;
}

关于c++ - Switch 语句输出错误的成本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26064086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com