我是c ++的新手,我正在尝试完成我的第一个任务。我不需要决定,但我想知道我做错了什么?这是我的代码:
#include <iostream>
using namespace std;
int main(){
int chTenders;
int frOrders;
int macCh;
int drinks;
int sauces;
float tip;
float subtotal;
subtotal = chTenders + frOrders + macCh + drinks + sauces + tip;
cout << "How many chicken tenders would you like?\n";
cin >> chTenders;
cout << "How many orders of fries would you like?\n";
cin >> frOrders;
cout << "How many orders of mac and cheese would you like?\n";
cin >> macCh;
cout << "How many drinks would you like?\n";
cin >> drinks;
cout << "How many sauces would you like?\n";
cin >> sauces;
cout << "How much would you like to tip?\n";
cin >> tip;
cout << "====Slim's Order====\n";
cout << "Subtotal $" << subtotal << endl;
return 0;
}
当我编译并运行它时,它给了我$ 2.60929e + 08而不是6.0:
How many chicken tenders would you like?
1
How many orders of fries would you like?
1
How many orders of mac and cheese would you like?
1
How many drinks would you like?
1
How many sauces would you like?
1
How much would you like to tip?
1
====Slim's Order====
Subtotal $2.60929e+08
答案 0 :(得分:2)
我认为您的计算顺序刚刚结束。 subtotal
是在您将输入值接收到被加数(chTenders
,frOrders
等)之前计算出来的。将subtotal=...
行移至cin << tip
语句之后。
答案 1 :(得分:0)
要详细说明原因,您要在之前中计算小计的值,然后将所有值分配给变量。在C ++中,在为变量分配值之前,对其进行访问的结果基于某个其他进程曾经写入该位内存的内容。因此,您实际上计算了一个垃圾值,然后要求用户输入。在C ++中,在定义变量的同时初始化变量通常被认为是一种好习惯。