C++ 默认值在开关语句中不起作用
c++ default not working in switch statement
这里编程相当新。我无法让 switch 语句中的默认代码正常工作。我希望它显示错误并在输入任何不在范围内的数据输入后立即退出。出于某种原因,它会转到 switch
语句之后的下一个cout
行。
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
int main()
{
char choice;
const double P=8.00, A=10.50, B=12.50;
double t,w,price;
cout<<"nPlease enter the state code: ";
cin>>choice;
cout<<"nPlease enter the Parcel's weight in KG: ";
cin>>w;
switch (choice)
{
case 'P':
case 'p':
t=w*P;
price=P;
break;
case 'A':
case 'a':
t=w*A;
price=A;
break;
case 'B':
case 'b':
t=w*B;
price=B;
break;
default:
cout<<"Error. Please Re-enter. Exiting";
break;
}
cout<<setw(80)<<setfill('*')<<"*"<<endl;
cout<<"nState code: "<<choice<<endl;
cout<<"Weight <KG>: "<<w<<endl;
cout<<"Price <RM>: "<<price<<endl;
std::cout<<std::fixed;
std::cout<<std::setprecision(2);
cout<<"Total Price <RM>: "<<t<<endl;
cout<<"nThank you and Please Come Again"<<endl;
cout<<setw(80)<<setfill('*')<<"*"<<endl;
return 0;
}
如果要在default
情况下结束程序,则需要在break
之前调用exit(some_status)
。 否则,break
只会导致 switch
语句结束,并且您在switch
块之后继续。
您需要在
出现错误消息后结束程序。您可以使用对 exit(( 的调用或返回语句。
相关文章:
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 默认标签显然在 switch 语句中不起作用
- C++ 中断语句不起作用
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 使用 cin、if 语句和数组不起作用
- (C++) IF 语句似乎根本不起作用
- 为什么当我输入字符时,这个特定的 cin.get() 语句在C++中不起作用?
- QTranslator 在 if 语句中使用时不起作用
- 我的开关语句在C++中不起作用
- 切换语句不起作用 c++ 和 D:\c++ dev-c\Makefile.win 目标"abc.o"的配方失败
- C++ 默认值在开关语句中不起作用
- C++ SQLite3 准备的删除语句不起作用
- 如果语句在我的代码中不起作用
- 一个'case'在简单的'switch'语句中不起作用
- 我的程序在SCANF语句之后不起作用
- std::cin 语句不起作用 C++
- 为什么我的 if 语句不起作用
- C++ 递增在 If else 语句中不起作用
- if 语句在 for 循环中不起作用
- 我的 for 循环之后的代码不起作用,for 循环后的打印语句不会被打印