我正在尝试编写一个简单的计算程序,但答案一直回到0 [英] I am trying to write a simple calculation program but the answer keeps coming back as 0
本文介绍了我正在尝试编写一个简单的计算程序,但答案一直回到0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我花了几个小时试图弄清楚为什么这会归零,如果有人可以帮助的话,那会很棒。
I have spent a couple hours trying to figure out why this comes back as 0 If someone could help that would be great.
1 /*Written by Connor Green*/
2 /*CISP 1010 01/28/17*/
3
4 #include <iostream>
5 using namespace std;
6
7 int main()
8
9
10 {
11 int carton_size, number_cartons, eggs_per_omelette, number_of_omelettes;
12 /*This will tell you how many omelettes you can make*/
13
14 number_of_omelettes = carton_size * number_cartons / eggs_per_omelette;
15 cout << "Welcome to the Egg Ordering Guide.\n";
16 cout << "How many eggs do you want per carton? (12, 18, or 25):\n";
17 cin >> carton_size;
18 cout << "How many cartons?:\n";
19 cin >> number_cartons;
20 cout << "How many eggs in an omelette? (2 or 3):\n";
21 cin >> eggs_per_omelette;
22 cout << "You can make ";
23 cout << number_of_omelettes;
24 cout << " omelettes with this amount of eggs.\n";
25
26 return 0;
27 }
推荐答案
这是因为您计算 number_of_omelettes
之前获取此计算的输入变量。将计算结果移到输出之前:
That's because you calculate number_of_omelettes
before getting the input variables for this calculation. Move that calculation to just before outputting it:
...
number_of_omelettes = carton_size * number_cartons / eggs_per_omelette;
cout << "You can make " << number_of_omelettes << " omelettes with this amount of eggs.\n";
此外,请注意除法 /
运算符在乘法 *
运算符之前,由于整数除法,结果可能为零。为避免这种情况,请使用括号强制乘法运算除以:
Also, beware that the division /
operator precedes the multiplication *
operator, which could result in zero due to integer division. To avoid this, force the multiplication to precede the division, using parentheses:
number_of_omelettes = (carton_size * number_cartons) / eggs_per_omelette;
这篇关于我正在尝试编写一个简单的计算程序,但答案一直回到0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文