我应该制作一个运输程序,询问用户一些基本问题。 以下是说明:在线购物者搜索网络以查找商品,购买商品来自税率最低的州。编写一个简单的C ++程序来执行以下操作:询问用户项目的单价,购物者想要购买的商品数量,第一个州的名称,第一个州的税率,以及第二州和第二州的税率。然后,计算每个州的总成本,并决定购物者应该从哪个州购买该物品。向购物者显示以下内容:单位项目成本,购买的商品数量,第一个州的名称和税率,第二个州的名称和税率,以及您对购物者应从哪个州购买的建议
列出程序中的所有文字和变量。
到目前为止,这是我的代码:
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
double itemPrice, numberItem, taxRate, totalCost;
double stateTax1, stateTax2;
int stateName1, stateName2;
// ask the item's price
cout << "What is the price of the item?\n";
cin >> itemPrice;
// ask the # items
cout << "How many items are you going to purchase?\n";
cin >> numberItem;
// ask the name of the first state
cout << "What state are you having it shipped to?\n";
cin >> stateName1;
// ask the tax rate of the first state
cout << "What is the tax rate in " << stateName1 << "?\n";
cin >> stateTax1;
// ask the name of the second state
cout << "What state are you having shipped from?\n";
cin >> stateName2;
// ask the tax rate of the second state
cout << "What is the tax rate in " << stateName2 << "?\n";
cin >> stateTax2;
// first if the first state has a lower tax rate
// else if second state has lower tax rate
if (stateTax1 < stateTax2)
{
totalCost = itemPrice * numberItem * stateTax1;
cout << "The item cost is " << itemPrice << ".\n";
cout << "The number of items is " << numberItem << ".\n";
cout << "The name of the first state is " << stateName1 << ".\n";
cout << "The tax rate of the first state is " << stateTax1 << ".\n";
cout << "The name of the second state is " << stateName2 << ".\n";
cout << "The tax rate of the second state is " << stateTax2 << ".\n";
cout << "You should consider purchasing the item from " << stateName1 << ".\n";
}
else
{
totalCost = itemPrice * numberItem * stateTax2;
cout << "The item cost is " << itemPrice << ".\n";
cout << "The number of items is " << numberItem << ".\n";
cout << "The name of the first state is " << stateName1 << ".\n";
cout << "The tax rate of the first state is " << stateTax1 << ".\n";
cout << "The name of the second state is " << stateName2 << ".\n";
cout << "The tax rate of the second state is " << stateTax2 << ".\n";
cout << "You should consider purchasing the item from " << stateName2 << ".\n";
}
return 0;
}
我的问题是如何让stateName变量正常工作。我确信这是我应该知道的一些基本字符串,但我不知道。除此之外,我相信我的其余代码正常工作。虽然任何和所有提示都将非常感激。
答案 0 :(得分:2)
&#34;向购物者显示以下内容:单位项目成本,购买的商品数量,第一个州的名称和税率,第二个州的名称和税率以及您的推荐购物者应该从哪个州购买。&#34;
代码中的变量定义
int stateName1, stateName2;
// ^^^
将仅接受输入语句的整数数值
cin >> stateName1;
无论何时输入类似
的内容Oklahoma
在输入提示符中,std::cin
将设置为fail()
状态,并且忽略进一步输入,除非您致电std::cin.clear();
&#34;我的问题是如何让stateName变量正常工作。&#34;
您可能希望接受stateName1
和stateName2
的字母数字输入,因此类型必须为std::string
,而不是int
std::string stateName1, stateName2;
应该是合适的(请注意,您需要#include <string>
代替#include <cstring>
才能执行此操作。