c++ - 如何在 C++ 中实现字符输入验证
问题描述
我需要创建一个程序来计算正在构建的表格的价格。
main() 函数应调用以下函数:
一种功能,它接受标准的与桌子一起使用的椅子数量。
接受标准的表表面积(以 m2 为单位)的函数。
接受标准的用于建造桌椅的木材类型的功能;“m”代表桃花心木,“o”代表橡木,“p”代表松木。理想情况下,任何其他条目都应被拒绝。
一个函数,它采用椅子的数量 (N)、桌子的表面积 (S) 和木材的类型 (x) 来计算价格。一张桌子的价格是 x(S + 1/2N),其中松木、橡木和桃花心木的 x 分别为 50 美元、100 美元和 150 美元。
显示购买详情的功能。
目前结果:
目前我的代码只会计算带有'm'(桃花心木)而不是其他两种材料的桌子的价格。例如:
Number of chairs: 5
Surface area of table (m2): 5
Wood type: m
Total = 1125
如果我将木材类型更改为“o”或“p”,将产生相同的价格。
代码:
#include <iostream>
using namespace std;
int main(){
int N;
cout << "Number of chairs: ";
cin >> N;
int S;
cout << "Surface area (in meters squared) of the table: ";
cin >> S;
cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
char x;
cin >> x;
while(x != 'm' && x != 'o' && x != 'p'){
cout << "Error. Invalid input. Please try again" << endl;
cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
cin >> x;
}
int total;
if(x = 'm'){
total = 150*(S + (0.5*N));
} else if(x = 'o'){
total = 100*(S + (0.5*N));
} else if(x = 'p'){
total = 50*(S + (0.5*N));
}
cout << "--------------------\n";
cout << "Details of purchase:\n";
cout << "--------------------\n";
cout << "Number of chairs: " << N << endl;
cout << "Surface area of table (m2): " << S << endl;
cout << "Wood type: " << x << endl;
cout << "Total = " << total << endl;
return 0;
}
解决方案
#include <iostream>
using namespace std;
int main(){
float N;
cout << "Number of chairs: ";
cin >> N;
float S;
cout << "Surface area (in meters squared) of the table: ";
cin >> S;
cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
char x;
cin >> x;
while(x != 'm' && x != 'o' && x != 'p'){
cout << "Error. Invalid input. Please try again" << endl;
cout << "Type of wood ('m' = mahogony, 'o' = oak, 'p' = pine): ";
cin >> x;
}
float total=0.f;
if(x == 'm'){
total = 150.f*(S + (0.5f*N));
} else if(x == 'o'){
total = 100.f*(S + (0.5f*N));
} else if(x == 'p'){
total = 50.f*(S + (0.5f*N));
}
cout << "--------------------\n";
cout << "Details of purchase:\n";
cout << "--------------------\n";
cout << "Number of chairs: " << N << endl;
cout << "Surface area of table (m2): " << S << endl;
cout << "Wood type: " << x << endl;
cout << "Total = " << total << endl;
return 0;
}
推荐阅读
- c# - Xamarin Mac,将 CGImage 转换为 .NET System.Drawing.Image
- ruby-on-rails - 阿帕奇无法启动乘客
- c - 带有clang的C大数组中的奇怪分段错误
- visual-studio-code - Visual Studio Code 添加表格会删除以前的表格
- mongodb - MongoDB 连接数如何计算?
- widget - Magento 2:如何创建带有动态字段的小部件?
- python - 如何在文件更改时使用 Gulp 重新启动散景服务器?
- c# - Xamarin 表单中带有圆角skiasharp 矩形的倒计时动画
- android - 我没有在 android Oreo 上收到推送通知,但在较低版本上我收到了
- php - Laravel array_diff() 作为更改日志