因此,我试图让这个程序允许用户输入他们的数据4次。我希望程序调用每个功能,直到用户第四次输入它们,但它不允许我和只是停止在第二次尝试。有人能帮我解决这个问题吗?谢谢!
输出:
输入作物名称:玉米输入成本、产量、每蒲式耳价格,并增加数据:5 5 5最低利润最高利润最高利润玉米平均利润20000.00美元145000.00美元82500.00美元输入作物名称:输入成本、产量、每蒲式耳价格,并增加数据:豌豆最低利润最高利润平均利润20000.00美元145000.00美元8250 0.00美元输入作物名称: Enter成本,产量,价格每蒲式耳,并增加数据:最低利润最高利润平均利润$20000.00 $145000.00 $82500.00输入作物名称:输入成本,产量,每蒲式耳价格,和增加数据:最低利润最高利润平均利润$20000.00 $145000.00 $82500.00输入作物名称:输入成本,产量,价格每蒲式耳,并增加数据:最低利润,最高利润,平均利润$20000.00,$145000.00,$82500.00,按任意键继续。。。在这里输入代码
程序:
#include <iostream>
#include<iomanip>
#include<string>
#define ACRES 1000;
using namespace std;
//Function prototypes.
void getData(string*, float*, int*, float*, float*);
void calculate(float, int, float, float, float*, float*, float*);
void printResults(string, float, float, float);
int main()
{
string name;
float CostPerAcre, increase, bushel, MinNP, MaxNP, AvgProfit2, bestcrop;
int yield;
for(int i = 0; i <= 4; ++i)
{
getData(&name, &CostPerAcre, &yield, &bushel, &increase);
calculate(CostPerAcre, yield, bushel, increase, &MinNP, &MaxNP, &AvgProfit2);
printResults(name, MinNP, MaxNP, AvgProfit2);
}
//cout << endl << "Old MacDonald, you should plant " << bestCrop << endl << endl;
return 0;
}
// This function allows the user to input their data.
void getData(string *cropname, float *costpa, int *bpa, float *dpb, float *dpbincrease)
{
cout << "Enter the crop name: " << endl;
getline(cin, *cropname);
cout << "Enter cost, yield, price per bushel, and increase data: " << endl;
cin >> *costpa >> *bpa >> *dpb >> *dpbincrease;
}
// This function uses the data to calculate the projected range of net profit and the average net profit for each crop.
void calculate(float costpa, int bpa, float dpb, float dpbincrease, float *MnNP, float *MxNP, float *AvgProfit)
{
float MnGP, MxGP;
float costofCrop = costpa * ACRES;
MnGP = (bpa * dpb ) * ACRES;
MxGP = MnGP + (MnGP * dpbincrease);
*MnNP = (MnGP)-costofCrop;
*MxNP = (MxGP)-costofCrop;
*AvgProfit = (*MxNP + *MnNP) / 2;
}
// This function displays the minimum profit, maximum profit, and average profit.
void printResults(string cropname, float MnNP, float MxNP, float AvgProfit)
{
cout << setw(25) << right << "Minimum Profit" << setw(20) << right << "Maximum Profit" << setw(20) << right << "Average Profit" << endl;
cout << cropname << setw(5) << right << setprecision(2) << fixed << '$' << MnNP << setw(10) << right << setprecision(2) << fixed << '$' << MxNP << setw(10) << right << setprecision(2) << fixed << '$' << AvgProfit << endl;
}发布于 2016-02-25 21:41:21
在getData函数中,不要使用getline,请执行以下操作:
cin >> *cropname;为什么?就像他们在一个类似的问题中说的那样,“如果您在cin >> something之后使用cin >> something,您需要在中间从缓冲区中清除换行符”。
发布于 2016-02-25 21:51:33
在从控制台读取后插入该内容。
cin.clear();
fflush(stdin);或
cin.flush();或
cin.ignore(INT_MAX);取决于您正在运行的系统
https://stackoverflow.com/questions/35638639
复制相似问题