Hi guys, let me begin by saying thanks to all involved in the site. What a great resoarce for anyone learning C++. I myself am only a few weeks in as part of my electronics degree. I'm doing a past paper at the moment in preperation for my exam and I have a pretty simple question I hope someone can help me with.
I have written a very small program that takes some user inputs and totals them on a do while loop until the user enters 0 and then the total is displayed. To do this I've decrared an int total and I'm adding a int sub_total to it until I get the 0. The probelm is that the range is including the 0 and for 100 + 100 i will always get 198. I understand why this is but I'm not sure of the "correct way to go about making it work the way I'd like. Should I decrare a different variable or should I add 1 everytime? The later seems a bit messy.
Anyway, sorry for my rather newbie question and a big hello to all.
simply because I don't know any better to be honest. The value has to be displayed on the console and it has to be able to have a decimal point. A double i guess just looks untidy.
I'm a beginer, this is the beginer forum right :) ......
int main( void )
{
const int k = 10;
int a;
int b;
int total;
int sub_total;
do
{
cout<<endl<<"Please enter a value for a: ";
cin>> a;
cout<<endl<<"You entered "<<a<<" for a."<<endl;
if (a > 0)
{
cout<<endl<<"Please enter a value for b: ";
cin>> b;
sub_total = a*b*k;
cout<<endl<<"sub total is "<<sub_total<<endl;
total=sub_total+total+1;
}
You need to set a value for total before using it. Also there appears to be a spare set of '{' characters above and below your cout toward the bottom there.
EDIT: Oghmaosiris is right, switch the int's for doubles.
int main( void )
{
constint k = 10;
double a, b, sub_total, total = 0;
do
{
cout<<endl<<"Please enter a value for a: ";
cin>> a;
cout<<endl<<"You entered "<<a<<" for a."<<endl;
if(a > 0){
cout<<endl<<"Please enter a value for b: ";
cin>> b;
sub_total = a*b*k;
cout<<endl<<"sub total is "<<sub_total<<endl;
total+=sub_total;
}
elsebreak;
}while (a > 0);
cout<<endl<<"The total is "<<total;
getchar();
getchar();
return 0;
}
I think the main problem is that you needed your variables as doubles to take into account the possible decimals. and I think your do while loop was a little off. like Computergeek said.
Tho I don't really know what the outcome of your program should be. I'm confused by the k variable always multiplying things by 10.
Its just an exsorsise, the k variable should actually be 1.234 as it is in the question for the paper. Thats great, I feel like I'm learning fast with this stuff, I think I'll keep at it even after the exam, I'm sure its bound to come in handy if I ever actually become a controls engineer as I hope.