2

我一生都无法弄清楚我在腻子中的这些简单方程式有什么问题。我认为一切都设置正确,但我的输出与我的教授样本输出略有不同。

//This program is used to calculate total cost of painting.
#include <iostream>
#include <iomanip>
using namespace std;

//These are the function prototypes that will be used for the main function.
void displayInstructions(int &feet, float &price);
float paintprice (int feet, float price);
float laborprice (int feet);
float totalcost(float paint, float labor);
void displayoutput (float paint, float labor, float total, int feet);

int main()
{
  int feet=0;
  float price=0;
  float paint=0;
  float labor=0;
  float total=0;

  displayInstructions(feet, paint);
  paint=paintprice(feet, paint);
  labor=laborprice(feet);
  total=totalcost(labor, paint);
  displayoutput(paint, labor, total, feet);
  return 0;
}

void displayInstructions(int &feet, float &price)
{
  cout<<setw(35)<<"==================================="<<endl;
  cout<<setw(30)<<"Painting Cost Calculator" <<endl;
  cout<<setw(35)<<"===================================" <<endl;
  cout<<"This program will compute the costs (paint, labor, total)\nbased on th\
e square feet of wall space to be painted \
and \nthe price of paint." <<endl;
 cout<<"How much wall space, in square feet, is going to be painted?" <<endl;
  cin>>feet;
  cout<<"How much is the price of a gallon of paint?" <<endl;
  cin>>price;
}

float paintprice (int feet, float price)
{
  float paint;
  paint=((feet/115)*price);
  return paint;
}

float laborprice (int feet)
{
  float labor;
  labor=((feet/115)*18*8);
  return labor;
}

float totalcost (float paint, float labor)
{
  float total;
  total=(paint+labor);
  return total;
}

void displayoutput (float paint, float labor, float total, int feet)
{
  cout<<"Square feet:" <<feet <<endl;
  cout<<"Paint cost:" <<paint <<endl;
  cout<<"Labor cost:" <<labor <<endl;
  cout<<"Total cost:" <<total <<endl;
}

基于输入为英尺=12900,价格=12.00 油漆成本的最终输出应为 1346.09 美元 人工成本的最终输出应为 16153.04 美元

我分别得到:$1344.00、$16128.00

如果你能帮助我,这将是一个救生员。

4

2 回答 2

1

labor=(((float)feet/115)*18*8);应该解决您的正确性问题。同样与paint =

之所以可行,是因为C++ 计算的工作方式。在计算像 a+b 这样的表达式时,两者都会自动转换为最准确的通用类型

但是,当您将整数除以整数时,feet/115结果在分配给值之前被计算为 int。这意味着该计算中的小数位会丢失,因此您会失去准确性。floatlabor

例如,如果英尺 = 120,则答案feet/115将是 1,而不是 1.04。

解决此问题的另一种方法是通过编写 115.0f将 115 转换为浮点数

于 2012-11-07T01:33:08.083 回答
0

你的脚是一个整数,当整数相除时,它会忽略小数点后的数字,例如int a = 10; a/3 = 3 而不是 3.33333333。(float) 将您的 int 转换为浮动,因此它可以工作。

于 2012-11-07T01:32:23.647 回答