When I try to run the program to figure the amount it just displays what is in t
ID: 3642230 • Letter: W
Question
When I try to run the program to figure the amount it just displays what is in the array instead of running it through the equation I have it in.The program I have is:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
cout << fixed << setprecision(2);
//declare array
double prices[10] = {10.5, 25.5, 9.75, 6.0, 35.0, 100.4, 10.65, 0.56, 14.75, 4.78};
int index=0;
double price=0;
do {
cout << "Please enter the index of the price to update (1-10) > ";
cin>> index;
if (index < 1 || index > 10) break;
if( index==2) price= (price*0.10)+price;
if(index==10);
price= (price *0.02)+price;
if(index==1);
price=index -(price*0.10);
cout<<"Prices: "<<prices[index-1]<<endl;
}while (true);
system ("pause");
return 0;
}//end of main
Explanation / Answer
The code you posted does calculations using the double variable price in the do loop, but then the last statement of the do loop displayed the value of the array variable prices[index-1], that's why you couldn't see the results of your calculations.
I updated the code you posted to do all of the calculations on the array variable, (and a few minor changes), the program now displays the results of the calculations.
Updated source code follows...
==========================================================
using namespace std;
#include<iostream>
#include<iomanip>
int main()
{
cout << fixed << setprecision(2);
//declare array
double prices[10] = {10.5, 25.5, 9.75, 6.0, 35.0, 100.4, 10.65, 0.56, 14.75, 4.78};
int index=0;
double price=0.0;
do {
cout << "Please enter the index of the price to update (1-10) > ";
cin>> index;
if (index < 1 || index > 10) { // added braces to if statements, not strictly
break; // required, but it makes things more readable
}
else if(index==2) { // no semicolon at the end of an if
// your calculations were all using, price, not prices[]
prices[index-1] = (prices[index-1] * 0.10) + prices[index-1];
}
else if(index==10) { // no semicolon at the end of an if
// your calculations were all using, price, not prices[]
prices[index-1] = (prices[index-1] * 0.02) + prices[index-1];
}
else if(index==1) { // no semicolon at the end of an if
// your calculations were all using, price, not prices[]
prices[index-1] = prices[index-1] - (prices[index-1] * 0.10);
}
// since the cout was using prices[], I updated the calculations above
// to match... if the program is supposed to use the double price
// that you declared above, all of the prices[] in the do loop will
// need to be changed so they are all the same.
cout<<"Prices: " << prices[index-1] << endl;
} while (true);
system ("pause");
return 0;
} // end of main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.