|
-
August 19th, 2010, 11:05 PM
#15
Re: Will this code work?
 Originally Posted by TheGreatCthulhu
Oh, heavens...
 The last few post have been very straightforward, please try to concentrate.
Imagine you're the CPU executing the code, line by line. This is a part of your original program:
Code:
// You're interested in totalCharge, ignore other stuff.
int main()
{
//declare variables
float previousReadings = 0.0;
float currentReadings = 0.0;
float gallonsUsed = 0.0;
float totalCharge = 0.0; // OK. Now totalCharge = 0.0 [remember the value]
//enter input items
cout <<"Enter the current readings:"; // totalCharge hasn't changed [still 0.0]
cin >> currentReadings; // totalCharge hasn't changed [still 0.0]
cout <<"Enter the previous readings:"; // totalCharge hasn't changed [still 0.0]
cin >> previousReadings; // totalCharge hasn't changed [still 0.0]
//calculates the gallons used
gallonsUsed = currentReadings - previousReadings; // totalCharge hasn't changed [still 0.0]
//calculates the total charge -- BUT totalCharge hasn't changed [still 0.0]
if (totalCharge >= 16.67) // totalCharge hasn't changed [still 0.0], so...
{
// will this execute?
totalCharge = (gallonsUsed / 1000) *7;
cout <<"totalCharge:" << totalCharge << endl;
}
// etc...
so here is the corrected version
#include <iostream>
using namespace std;
int main()
{
//declare variables
float previousReadings = 0.0;
float currentReadings = 0.0;
float gallonsUsed = 0.0;
float totalCharge = 0.0;
//enter input items
cout <<"Enter the current readings:";
cin >> currentReadings;
cout <<"Enter the previous readings:";
cin >> previousReadings;
//calculates the gallons used and total charged
gallonsUsed = currentReadings - previousReadings;
totalCharge = (gallonsUsed / 1000) *7;
//calculates the total charge
if (totalCharge < 16.67)
{
totalCharge = 16.67;
cout <<"total charge:" << totalCharge << endl;
}
//end if
cout <<"gallons used:" << gallonsUsed << endl;
cout <<"total charge:" << totalCharge << endl;
return 0;
} //end of main function
does it make sense?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|