Re: Compare two numbers
On Sat, 2 Feb 2008 22:11:01 +0800, "Elynis Zhou"
<elynis_zhou@witjpn.com.cn> wrote:
Hi everyone,
I want to input two numbers(int style) to compare them.
Then set the lower one as the lower limit,and the upper one as the upper
limit.And add the lower to the upper one.But whatever I input,the programme
always display "Sum of -858993460 to -858993460 is -1717986920. The code is
as followed,
#include <iostream.h>
int main()
{
cout<<"Enter two numbers:";
int v1,v2;
cin>>v1>>v2;
int lower,upper;
if(v1<=v2){
v1=lower;
v2=upper;
}
else
v1=upper;
v2=lower;
The assignment operator assigns the right-hand side to the left-hand side,
so you reversed the order of identifiers in your assignment statements.
Perhaps using the iostream extraction operator just before got you
confused. Also, you forgot to make the else clause a compound statement,
i.e. you forgot the braces.
int sum;
for (int val=lower;val<=upper;++val)
sum+=val;
You forgot to initialize "sum". Uninitialized local variables start off
with essentially random values, and due to the previous mistake with the
assignments, all the variables in your calculation have indeterminate
values. Not good, but easy to fix. :)
Also, for fun and enlightenment, google "Gauss trick".
cout<<"Sum of"<<lower<<" to"<<upper<<" is"<<sum<<endl;
return 0;
}
And use spaces between these operators and identifiers to make your code
easier to read.
--
Doug Harrison
Visual C++ MVP