void_print_total(int price)
{
//Add your code here...
}
The fucntion should total the price passed from the caller function and print the result in one line everytime it is called according to the format below.
Price of item 1 is 15 and total is 15
Price of item 2 is 21 and total is 36
Price of item 3 is 14 and total is 50
Anyone can help me ? i have no idea how to start with this kind of questions.
Can it be done through one function returning void and taking one int argument?
Yes.
Indeed it must be done that way - that's what the original question asks. Changing the function signature (parameter list or return type) is to invent one's own question and answer that instead.
But how Chervil, please show us. I've been banging my head on this for the past hr
According to OP:
The fucntion (sic) should total the price passed from the caller function and print the result in one line everytime it is called according to the format below
I'm not sure all of these can be achieved with the (partial) function signature supplied - OP actually does not specify a return type though the name of the function suggests it might be void
OP actually does not specify a return type though the name of the function suggests it might be void
Yes - that worries me too. I've assumed it was some sort of typo - but making assumptions can be dangerous.
Still, I came up with two alternatives:
1 2 3 4 5 6 7 8 9 10
void print_total(int price)
{
staticint count = 0;
staticint total = 0;
++count;
total += price;
std::cout << "Price of item " << count << " is " << price
<< " and total is " << total << std::endl;
}
Or alternatively (and this might not be permitted)
1 2 3 4 5 6 7 8 9 10
int global_count = 0;
int global_total = 0;
void print_total(int price)
{
++global_count;
global_total += price;
std::cout << "Price of item " << global_count << " is " << price
<< " and total is " << global_total << std::endl;
}
Though the second version may breach the terms of the original question, it does have the advantage that the global variables can be reset if necessary.