Home > Mobile >  My pair <double, double> format function will not operate when called
My pair <double, double> format function will not operate when called

Time:12-15

I am writing a code with a pair <double, double> format function, but the function will not operate when called.

I am still learning C , so maybe this format just isn't the way to go. Here is the prompt question in case it helps or anybody needs it to see where I was trying to go with my code.

Write a function that calculates the total amount due on a receipt. Your function should be able to take in any number of decimal values and a sales tax rate. The function should return the subtotal (total of all items without tax) and the receipt total (total of all items with tax).

(Ex.) Given a sales tax rate of 8.25% (0.0825) and the following item prices: 1.35, 2.38, 3.56, 7.89, 10.25, 3.31, 5.67

Your function should calculate that the total without tax is 34.41 and the total with tax is 37.2488

And here is my code:

#include <bits/stdc  .h>
using namespace std;

pair <double, double> total(int itemCount, vector<double> itemPrices)
{
    double sum = 0;
    for (int i = 0; i < itemCount; i  )
    {
        sum  = i;
    }
  
    return {sum, sum   sum * 0.0825};
}

int main(int argc, char const * argv[])
{
    int itemCount = 0;
    cout << "Enter the number of items: ";
    cin >> itemCount;
    vector <double> itemPrices(itemCount);
    cout << "Enter item prices: " << endl;
  
    for(int i = 0; i < itemCount;   i)
    {
        cin >> itemPrices[i];
    }
  
    pair <double, double> val = total(itemCount, itemPrices);
    double totalWithoutTax = val.first;
    double totalWithTax = val.second;
    return 0;
}

I was told by a friend that this format would help, but I am struggling a bit with it.

Edit: Hmm, I think I might just need to scrap this code since I think it's a bit beyond what I understand of C right now. To clarify to anyone trying to get the issue is, the output I get when the code runs is:

Enter the number of items: 7
Enter item prices: 
1.35
2.38
3.56
7.89
10.25
3.31
5.67

From what I understand about functions is that, once defined, they are supposed to operate when called. But when I call the total() function, it does nothing and the program ends. So, I am really just confused.

CodePudding user response:

The problem is in the total function.

Change sum = i to sum = itemPrices.at(i), then add std::cout at the end of the program before returning zero.

cout << totalWithTax << '\n' << totalWithoutTax << endl;

CodePudding user response:

Because you are passing the value of vector instead of passing the reference of vector:

pair <double, double> total(int itemCount, vector &itemPrices)

  •  Tags:  
  • c
  • Related