目前正在研究某些东西,我想我已经知道了95%。
#include <iostream>
using namespace std;
char vehicle, car, truck, bus;
double cost;
int hoursParked;
int main()
{
cout << "Do you have a car, truck, or bus?" << endl << "c = car, t = truck,
b = bus" << endl;
cin >> vehicle;
if (cin == c) {
vehicle = car;
}
cout << endl << "How long were you parked?" << endl;
cin >> hoursParked;
if (vehicle == car) {
if (hoursParked <= 2) {
cost = 1.25 * hoursParked;
}
else {
cost = 1.25 * hoursParked;
cost = 1.50 * (hoursParked - 2) + cost;
}
}
cout << "Here is your receipt " << 1.25 * cost << endl;
}
这只是开始,我仍然必须添加公共汽车和卡车,但是我遇到的问题是试图弄清楚如何根据输入来分配变量。如果他们输入c,如何将他们的车辆分配给汽车,或者如果他们输入t,如何将其分配为卡车?
答案 0 :(得分:1)
我发现您的实施过程中可能需要一些帮助。
首先,您似乎正在将变量名称与字符常量混合在一起:
config.data …
因此,当您以一个字符作为输入时,例如在int var = 'c'; // variable holding the character 'c'
中,您想将其与“ c”(汽车),“ b”(公共汽车)等进行比较。
cin >> vehicle;
稍后再次将车辆与汽车char vehicle;
cin >> vehicle;
if (vehicle == 'c') {
//...
进行比较,在这里,您将变量名称为vehicle(应为'c','b'或't')的变量与变量car进行比较。内容可以是任何东西(可能为零)。
下面是一个快速重写,为您展示了一种解决此问题的方法的示例,还有很多其他方法,但我希望它可以帮助您入门:
if (vehicle == car) {
答案 1 :(得分:-1)
#include <iostream>
using namespace std;
int main()
{
cout << "Do you have a car, truck, or bus?\nc = car, t = truck, b = bus\n";
char vehicle; // declare your variables where they are used.
cin >> vehicle; // let the user input a character we can evaluate later
cout << "\nHow long were you parked?\n";
int hoursParked;
cin >> hoursParked;
double cost;
switch (vehicle) // evaluate the variable vehicle and switch upon its value
{
case 'c': // user input the letter 'c'
if (hoursParked <= 2) {
cost = 1.25 * hoursParked;
}
else {
cost = 1.25 * hoursParked;
cost = 1.50 * (hoursParked - 2) + cost;
}
break; // exit the switch. if there were no break execution would continue with case 't'
case 't':
// ... add your calculations for a truck
break;
case 'b':
// ... add your calculations for a bus
break;
}
cout << "Here is your receipt " << 1.25 * cost << '\n';
}