我被困在一个程序上,该程序收集用户关于股票买卖价格以及他们拥有多少股票的输入。我正在使用 for 循环根据他们希望处理的选项数量来测试条件。 profit 的值在每次循环后保存,但在循环退出时仅输出最终值。有没有一种方法可以在循环中保留分配给特定单个变量的总值并将它们相加并打印出来。
这是我的代码:
int _tmain(int argc, _TCHAR* argv[])
{
double buy = 0;
double sell = 0;
double shares = 0;
int options = 0;
double profit = 0;
double totalProfit = 0;
double *pBuy = &buy;
double *pSell = &sell;
double *pShares = &shares;
double *pProfit = &profit;
double *ptotalProfit = &totalProfit;
cout << "Please enter the number of stock option to process:" << endl;
cin >> options;
for ( int i = 0; i < options; i++)
{
cout << "Please enter the buy price for stock #" << i + 1 <<":" << endl;
cout << "$"; cin >> *pBuy;
cout << "Please enter the sell price for stock #" << i + 1 << ":" << endl;
cout << "$"; cin >> *pSell;
cout << "Please enter the shares for the stock #" << i + 1 <<":" << endl;
cin >> *pShares;
*pProfit = (*pSell - *pBuy) * *pShares;
}
*pProfit = (*pSell - *pBuy) * *pShares;
cout << "Total Profit is:" << "$" << *pProfit << endl;
system("pause");
return 0;
最佳答案
我想你想要以下内容。只需继续添加到 profit
变量即可。由于您没有通过指针或引用将此变量传递给另一个函数,因此不需要使用指针。
profit = 0;
for ( int i = 0; i < options; i++)
{
cout << "Please enter the buy price for stock #" << i + 1 <<":" << endl;
cout << "$"; cin >> buy;
cout << "Please enter the sell price for stock #" << i + 1 << ":" << endl;
cout << "$"; cin >> bell;
cout << "Please enter the shares for the stock #" << i + 1 <<":" << endl;
cin >> shares;
profit += (sell - buy) * shares;
}
cout << "Total Profit is:" << "$" << profit << endl;
关于c++ - 如何从for循环中获取值的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568204/