【问题标题】:I am trying to write a simple calculation program but the answer keeps coming back as 0我正在尝试编写一个简单的计算程序,但答案总是返回为 0
【发布时间】:2017-01-29 03:55:38
【问题描述】:

我花了几个小时试图弄清楚为什么返回为 0 如果有人可以提供帮助,那就太好了。

  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 }

【问题讨论】:

  • 您使用了哪些输入?整数数学会去掉小数部分。
  • 为什么在输入数据之前就开始计算? C++ 程序自顶向下运行。这不像是你在写一个公式,然后程序会神奇地使用这个公式。

标签: c++ calculator


【解决方案1】:

这是因为您在获取此计算的输入变量之前计算number_of_omelettes。将该计算移至输出之前:

...
number_of_omelettes = carton_size * number_cartons / eggs_per_omelette;
cout << "You can make " << number_of_omelettes << " omelettes with this amount of eggs.\n";

另外,请注意除法 / 运算符在乘法 * 运算符之前,由于整数除法,这可能导致零。为避免这种情况,请使用括号强制乘法在除法之前:

number_of_omelettes = (carton_size * number_cartons) / eggs_per_omelette;

【讨论】:

  • 谢谢。我知道这很简单
猜你喜欢
  • 2017-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
相关资源
最近更新 更多