0

Who doesn't like discounts? Exercise C++ [SPOILER]

Hey all, Been blocked on this exercise for a while now. Here's the subject: A supermarket has launched a campaign offering a 15% discount on 3 items. Write a program that takes the total price for every purchase as input and outputs the relevant discount. ## code ## #include <iostream> using namespace std; int main() { int purchaseAmount = 0; int totalPrice; //your code goes here do { cin >> totalPrice; float purchaseAmount = totalPrice * 0.15; cout << purchaseAmount << endl; } while (totalPrice); // Tried (totalPrice < 3) return 0; } The result is an infinite loop with the last input. I know there's a detail I've miss but still can't figure out what T_T Any tips? :/

22nd Aug 2021, 9:56 AM
Da Silva Miguel
Da Silva Miguel - avatar
2 odpowiedzi
+ 3
Right now, you continue iterating while "totalPrice" is unequal to zero. However, if there is no more input, std::cin will not write anything into it, meaning it will keep its value from the third iteration and result in an infinite loop. To fix this, you could introduce a counter variable: int iterations = 3; ... do { ... } while ( --iterations ); Or check if the input stream is still usable: do { ... } while ( cin.good() ); But, to be honest, if there are always a fixed number of inputs, a for loop would probably be a better suit than a do-while loop, this task is kind of a bad example for it.
22nd Aug 2021, 10:07 AM
Shadow
Shadow - avatar
- 1
@Shadow, tried the (while(cin.good()); well, the problem is that I haven't learn that part x) Tried to the 1st and it work perfectly. I might have found my problem, is that I was focusing on the code bellow // your code goes here. Thx mate! :)
22nd Aug 2021, 10:12 AM
Da Silva Miguel
Da Silva Miguel - avatar