【发布时间】:2022-12-05 06:55:47
【问题描述】:
这是我需要用 C++ 编写的问题 The question/problem
我似乎不知道我的代码的问题。
这是代码:
#include <iostream>
using namespace std;
int main(void)
{
cout << "Total Purchase Cost: Php ";
double total;
cin >> total;
cout << "Loyalty Card Type: ";
int cardType;
cin >> cardType;
double discount = 0;
double type1 = 0.10;
double type2 = 0;
double type3 = 0.15;
if (cardType == 1)
discount = total * type1;
if (cardType == 2)
discount = total * type2;
if (cardType == 3)
discount = total * type3;
else
cout << "Invalid Card";
cout << "Discounted Cost: Php \n" << discount;
return 0;
}
当我尝试运行它时,折扣价是正确的,计算是正确的,输出文本“Discounted Cost: Php ---”似乎工作正常。但是当我开始添加 else 语句时,当我在 if 语句中输入无效数字时,它会输出“Invalid Card”消息。但是当我输入一个有效数字时,else 语句仍然打印出来,即使它不应该打印出来。
【问题讨论】:
-
使用范围,卢克,使用范围。
-
您是否意识到您的
else仅附加到最后一个if?你是否也意识到if语句都是独立运行的?您想使用 if/else if/else 或开关。投票关闭拼写错误。 -
如果您将所有图片和图像上传到 Facebook 或 Twitter,效果会更好,而这些网站正是为此而设计的。在 Stackoverflow 上,如果所有相关信息都包含在问题中,它会工作得更好作为纯文本, 这样任何人都可以剪切/粘贴显示的代码并自己尝试。您能否从问题中删除所有图像和照片,并包含与纯文本相同的信息?
标签: c++ if-statement switch-statement