One does not simply...not know!!!

hey all...Im trying to make a converter (miles to km)-nothing new really. and there's the method of taking three variables and then printing the result eg say a multiplication. And then there's this;

#include <iostream>
using namespace std;
int main()
{int miles;
double kilometers=miles*1.609;
cout <<"Miles=?";
cin >> miles;
cout <<"Kilometers= ";
cout <<kilometers;
return 0;
}

why is it that this program cant work??? its giving me ridiculous values when i run it.
Last edited on
Becouse you are initialising kiloters before you know what miles is.
Because you are calculating the kilometers BEFORE you enter the miles. This is bad. It cannot work. You must get the number first, and then do the calculation.

You have to enter the value for miles, and THEN, AFTER that, you can calculate kilometers.

Edit: I've been NiNJARRED. :p
Last edited on
I had actually done that initially..this was my initial program

{int miles;
double kilometers;
cout <<"miles= ";
cin>>miles;
miles=1.609*kilometers;
cout<<"kilometers=" <<kilometers;
return 0;
}

and when i test it, the result was still gibberish with a crazy exponential. could it be a compiler problem??? I thought maybe its coz im not initialising the variables so thats why i tested the earlier quoted version (with a lot of doubt) but then that didnt solve anything either, as noted duly
1
2
3
4
5
6
7
8
{int miles;
double kilometers;
cout <<"miles= ";
cin>>miles;
miles=1.609*kilometers;
cout<<"kilometers=" <<kilometers;
return 0;
}


So in this code, you fetch a value for miles from the user, and then you change that value of miles using a value of kilometers that you did NOT fetch from the user (so it will be some random value), and then you output that random value of kilometers (and do nothing with the value of miles you calculated). So why are you surprised that it's some crazy random value?

Here is what you need to do:

Get value for miles from user.
Multiply that number by 1.609 (store this as kilometers).
Output kilometers.
Last edited on
{int miles;
double kilometers;
cout <<"miles= ";
cin>>miles;
kilometers=1.609*miles;
cout<<"kilometers=" <<kilometers;
return 0;
}

Ok! so i switched line 5 and wrote it as such (thanks to your stern response); kilometers = 1.609 * miles instead of miles=1.609 * kilometers as shown above and guess what!!! IT WORKED. hehehe. ok i just thought that after declaring the variables, it wouldnt matter which side of the operator you place them , c++ would be able to understand. Guess my mistake was thinking a software was a human mind. THANKS ALOT Moschops...pizza on me- (as long as you can find ur way to Kenya). otherwise, thanks a bunch. I feel stupid, but more importantly, I've learnt.
Topic archived. No new replies allowed.