c++ - 保存累加器的每次迭代?

标签 c++ loops c++11 counter accumulator

(是的,这是作业,但已经完成,我现在只是想改进它以进行练习)

这基本上是一个销售计算器,允许您对销售项目进行多个输入,然后显示总计、销售税和总计。

我想做的修改是,我希望能够在变量中保存每个项目的成本,而不会重叠内存,然后能够在总计之上调用它们,所以您可以看到每件商品的值(value)。

============================================= ============================

//importing libraries for cin and cout, as well as setw() and setprecision()
#include <iostream>
#include <iomanip>
using namespace std; //sets all code to standard syntax

int main(){ //initializes the main function

    //initializing variables
    char answer = ' ';
    int saleItems = 0;
    double saleTax = 0.0;
    double grandTotal = 0.0;
    double itemValue = 0.0;
    double titemValue = 0.0;
    double taxPerc = 0.0;

    //begins a post-test loop
    do {
        titemValue = 0.0; //makes sure the accumulator resets WITHIN the loop

        //prompts for sale items amount
        cout << "How many sales items do you have? : ";
        cin >> saleItems;

        //creates a loop that displays the prompt for each iteration of saleItems
        for (int x = 1; x <= saleItems; x += 1){
            cout << "Enter in the value of sales item " << x << " : $";
            cin >> itemValue;
            titemValue += itemValue; //accumulator for adding up the iterated values
        }

        //prompts the user to enter a sales percentage
        cout << endl << endl;
        cout << "Enter in the sales tax percentage(Enter 10 for 10%): ";
        cin >> taxPerc;
        cout << endl << endl;

        //processes the variables after taxPerc has been given
        saleTax = titemValue * (taxPerc / 100);
        grandTotal = titemValue + saleTax;

        //sets decimal precision to 2 places
        cout << fixed << setprecision(2);

        //displays receipt with the calculated and input values
        cout << "********************************************" << endl;
        cout << "********  S A L E S  R E C E I P T  ********" << endl;
        cout << "********************************************" << endl;
        cout << "**                                        **" << endl;
        cout << "**                                        **" << endl;
        cout << "**                                        **" << endl;
        cout << "**                                        **" << endl;
        cout << "**  Total Sales            $" << setw(9) << titemValue << "     **" << endl;
        cout << "**  Sales Tax              $" << setw(9) << saleTax << "     **" << endl;
        cout << "**                          ----------    **" << endl;
        cout << "**  Grand Total            $" << setw(9) << grandTotal << "     **" << endl;
        cout << "**                                        **" << endl;
        cout << "**                                        **" << endl;
        cout << "********************************************" << endl << endl << endl;

        //prompts user to begin loop again
        cout << "Do you want to run this program again? (Y/N):";
        cin >> answer;
        answer = toupper(answer);
        cout << endl << endl;

        } while (answer == 'Y');

============================================= ============================

因此,从本质上讲,我需要能够将每个 itemValue 保存为多个不同的值,而无需循环重复自身,只需替换它们,考虑到累加器将继续循环,我真的不知道我该怎么做,并将 itemValue 值相加。

最佳答案

这是使用简单数组存储项目值的一种方法。

在顶部声明一个数组。注意:你必须给它一个固定的大小。有多种方法可以使大小可变,但它们会变得更复杂(例如 vector )。最好使用常量而不是硬编码数字来指定大小,因为稍后您将需要该常量。

const int maxSaleItems = 100;
double itemValues[maxSaleItems];

在您向用户询问项目数量后,尽可能确保他们没有输入太大的数字。

    cout << "How many sales items do you have? : ";
    cin >> saleItems;
    if (saleItems > maxSaleItems) {
        cout << "Sorry, I can only handle " << maxSaleItems << " items.";
        continue;
    }

在输入项目值的循环内,将项目值保存到数组中:

        cout << "Enter in the value of sales item " << x << " : $";
        cin >> itemValue;
        titemValue += itemValue; //accumulator for adding up the iterated values
        itemValues[x - 1] = itemValue;

注意 x-1在数组访问中——数组是基于 0 的(即它们的索引从 0 开始)。通常我会循环 x来自 0< saleItems ,但我不想更改您现有的循环。

打印收据时,添加一个打印出所有值的循环(您需要添加格式):

    cout << "**                                        **" << endl;
    for (int x = 1; x <= saleItems; x += 1){
       cout << "** Item " << x << " $" << itemValues[x-1] << "   **" <<endl;
    }
    cout << "**                                        **" << endl;

正如我在评论中所说,使用 std::vector会更好,但如果您还没有做到这一点,数组也可以。

编辑:简单 vector例子。 要添加 vector ,您需要包含适当的标题:

#include <vector>

不需要maxSaleItems任何更多,因为 vector 可以增长。声明 vector 变量。 <double>使其成为包含 double 的 vector 值(value)观:

std::vector<double> itemValues;

在循环中,不是按位置设置新项目的数组值,而是使用 push_back 将其添加到 vector 的末尾.

    cout << "Enter in the value of sales item " << x << " : $";
    cin >> itemValue;
    titemValue += itemValue; //accumulator for adding up the iterated values
    itemValues.push_back(itemValue);

打印收据代码,可以完全保留为数组版本,因为您可以访问数组之类的 vector :

cout << "**                                        **" << endl;
for (int x = 1; x <= saleItems; x += 1){
   cout << "** Item " << x << " $" << itemValues[x-1] << "   **" <<endl;
}
cout << "**                                        **" << endl;

您还可以进行其他更改来制作 vector版本更简单,但我想尽可能少地更改。

关于c++ - 保存累加器的每次迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38297649/

相关文章:

c++ - 有没有办法在继承构造函数时访问初始化列表?

c++ - 移植到 64 位时如何避免 size_t 到 int 转换警告?

java - java中调用游戏中fps tick的paint方法

c++ - qt:继承父类(super class)的 invokemethod 返回值不正确

linux - 菜单和子菜单,然后返回到Linux上的菜单脚本

java - 有没有办法让这个代码片段更有效率?

c++ - 使用可变参数模板进行类型推导和参数传递

c++ - 实现 RGBtoHSV C++,错误的 H 输出

c++ - 从链表中删除元素 (C++)

c++ - 如何从通过 Windows MiniDump 调用生成的核心转储中获取堆栈跟踪?