c++ - 如何从for循环中获取值的总和

标签 c++ visual-c++

我被困在一个程序上,该程序收集用户关于股票买卖价格以及他们拥有多少股票的输入。我正在使用 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/

相关文章:

c++ - CToolbar 自定义对话框中图标的自定义绘制

c++ - 文件中存储的对象的字符串成员

c++ - 为什么 boost::serialization 不检查 XML 文件中的标签名称?

windows - 如果windows应用程序消息队列中没有消息,那么消息循环还会继续运行吗?

c# - DLL导入使用SYSTEMTIME

c++ - 我可以将 std::basic_string 用于非字符类型的东西吗?

c++ - C++ DLL程序退出时: Run-Time Check Failure #2

c++ - 在 Mac 上检测 PDF 打印

c++ - MFC 应用程序在启动时关闭

c++ - 英特尔 OpenCL SDK - 头文件在哪里?