when multiplying a set of int's and converting the result to a long I get a different answer as opposed to when I multiply a set of doubles and convert the result to a long. eg:
int a = 5;
int b = 5;
int c = 7;
int d = 6;
int ee = 6;
int f = 8;
int g = 9;
int h = 6;
int i = 6;
int j = 4;
int k = 8;
int l = 9;
int m = 5;
long x = a * b * c * d * ee * f * g * h * i * j * k * l * m;
double aa = 5;
double ab = 5;
double ac = 7;
double ad = 6;
double aee = 6;
double af = 8;
double ag = 9;
double ah = 6;
double ai = 6;
double aj = 4;
double ak = 8;
double al = 9;
double am = 5;
long y = (long)(aa * ab * ac * ad * aee * af * ag * ah * ai * aj * ak * al * am);
Can anyone tell me why this happens? Thank you
Program to Multiply Two Numbersprintf("Enter two numbers: "); scanf("%lf %lf", &a, &b); Then, the product of a and b is evaluated and the result is stored in product . product = a * b; Finally, product is displayed on the screen using printf() .
Most C programs perform calculations using the C arithmetic operators (Fig. 2.6). The asterisk (*) indicates multiplication and the percent sign (%) denotes the remainder operator, which is introduced below.
In C Programming, Multiplication Operator is used to find the product of two numbers. The operator takes two operands and returns the product of these two operands.
In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.
You've got an integer overflow, since whenever you multiply two int
you have int
:
this is interpreted as Int32
so far
a * b * c * d * ee * f * g * h * i * j * k * l * m
and only than converted into Int64
(long
). To correct the implementation, declare
all the variables initially being long
e.g.
long a = 5;
long b = 5; // actually, not necessary, since a * b will be long, but safer
long c = 7;
...
long m = 5;
long x = a * b * c * d * ee * f * g * h * i * j * k * l * m;
That's probably because the result of your multiplication is too big to hold in an Int32 - yet it can be held in a double.
To be a bit more specific look at x and y in hexadecimal:
x = 0x000000007994b000
y = 0x000000057994b000
An Int32
can only hold the lower 8 hex values. This is why x
is the wrong number. The lowest 8 hex-values are correct, but the top is cut off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With