【问题标题】:Read from standard input and associate it with the following standard input从标准输入读取并将其与以下标准输入相关联
【发布时间】:2018-03-17 16:03:20
【问题描述】:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
  double labor = 3;
  double squareFt = 160;
  double oneGallon;
  double chargePerHour = 28; //charger per hour for labor
  double numOfRooms; //input from user
  double sqFootage; //input from user 
  cout<<"Welcome to Artistic Solutions."<<endl;
  cout<<"Please enter the number of rooms that will be painted."<<endl;
  cin>>numOfRooms);
  cout<<"Please enter the squart footage of wall space in each room."<<endl;
  cin>>sqFootage);

  return 0;
}

这是一项实验室作业,它计算油漆工作的成本。它询问需要粉刷多少个房间以及每个房间的平方英寸。有没有办法关联“numOfRooms”和“sqFootage”?我想做的是尽量减少重复询问每个房间的平方英尺。使用数组和指针会有帮助吗?

【问题讨论】:

  • cin&gt;&gt;sqFootage); 你将需要一个循环(并且少一个')')来读取多个房间的平方英尺。停止编写代码,并整理一份你需要做的事情的清单,一份需求文档。一旦你有了这些,找出完成要求所需的顺序,然后你就会更好地了解你真正需要做什么,并希望有一个攻击计划的开始。
  • 想想如何使用循环和函数来减少重复。

标签: c++


【解决方案1】:

不,您不需要数组,因为您不必存储数据。

您也无法真正避免重复,因为无论如何用户都必须插入所有不同的值。但是,您可以保存代码并只编写一次。

您可以使用for 循环根据需要多次请求sqFootage

int sumSqFootage = 0, numOfRooms;
cout...
cin >> numOfRooms;
for (int i = 0; i < numOfRooms; i++)
{
    int sqFootage;
    cout...
    cin >> sqFootage;
    sumSqFootage += sqFootage;
}

【讨论】:

  • 您好,感谢您的建议。但是,程序要求用户输入房间数,所以假设用户输入数字 4。我将不得不要求用户输入平方英尺 4 次,但我想最小化,以免如此重复。让我知道这是否能解决一些问题。
  • @user237448 等等,每个房间的面积都不一样?
  • 是的,所以我想这样做:1 平方英尺 - 1 个房间,2 平方英尺 - 2 个房间等等。
  • 哦,我想我明白了。
  • @user2373448 不需要重复代码,但重复是绝对必须的。您将不得不多次请求输入并进行多次计算,但您可以一遍又一遍地使用完全相同的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 2013-03-30
  • 2012-02-17
  • 2013-03-18
  • 2011-11-15
  • 2012-04-25
相关资源
最近更新 更多