+ 2
Loop problem
Please how do I stop the loop from the third line onwards. To understand what I am asking, when you run the code, enter three multiple inputs, each per line. The third output loops indefinitely, why? Thanks in advance Edit: 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. Sample Input 15000 4000 6700 Sample Output 2250 600 1005 Explanation 2250 represents a 15% discount for a 15000 purchase; 600 for 4000 and 1005 for 6700 accordingly. https://code.sololearn.com/ca25A10a24a1/?ref=app
11 Antworten
+ 6
this will break out of the loop
int purchaseAmount = 3;
int totalprice;
do
{
cin >> totalprice;
int discount = totalprice - (0.85*totalprice);
cout << "" << discount << endl;
purchaseamount--;
}
while( 0 < purchaseAmount);
+ 5
#include <iostream>
using namespace std;
int main()
{
int purchaseAmount = 3;
int totalPrice;
do {
cin >> totalPrice;
//we'll use float instead of int because we don't want to round
float discount = 0.15 * totalPrice;
cout << discount << endl;
purchaseAmount--;
}
while(0 < purchaseAmount);
return 0;
}
+ 1
Maybe you don't understand how your code works ? Which seems quite impossible ,anyhow it works fine for me
Enter the negative number to stop loop
+ 1
- Purchase amount is set to 0
So ( price > 0) is a infinite loop even with the discount hitting infinite times it will never touch zero
- you can set up a for loop and an dynamic array if the list size is unknown like for the prices. Solo learn has an awesone quick tutorial.
+ 1
Giovanni many thanks, but the list size is known, it's three.
+ 1
//this is the simplest way to get correct answer
#include <iostream>
using namespace std;
int main()
{
int purchaseAmount = 0;
int totalPrice;
//your code goes here
do{
cin>>totalPrice;
cout<<totalPrice * .15<<endl;
purchaseAmount++;
}
while( purchaseAmount <3);
return 0;
}
+ 1
/* Here is a perfect example of the do...while loop.
I changed the data type of totalPrice to float as the discounted price includes decimals. Alternatively, you can create a new float data type and change the following section from
totalPrice = totalPrice * 0.15;
To
discount = totalPrice * 0.15;
Multiplying a decimal by a number finds the percentage, in this case 15%. You can also increase a number by a percentage with the same method. E.g totalPrice * 1.15 = 15% increase. A little bit of maths for you :) */
#include <iostream>
using namespace std;
int main()
{
int purchaseAmount = 0;
float totalPrice;
//your code goes here
do {
cin >> totalPrice;
purchaseAmount++;
totalPrice = totalPrice * 0.15;
cout << totalPrice << endl;
} while (purchaseAmount < 3);
return 0;
}
0
what are you using the loop for?
0
Abhay I have updated the question now, kindly check.
0
Giovanni Do you have any idea of why it isn't showing decimals? For example, if a user inputs 6930, the output is supposed to be 1039.5 but it only shows 1039.