Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplication in C# error

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

like image 262
Ka0s Avatar asked Jan 12 '15 12:01

Ka0s


People also ask

How do you multiply in C?

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() .

Is there multiplication in C?

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.

What is multiplier in C?

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.

What is %d in C programming?

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.


2 Answers

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;
like image 52
Dmitry Bychenko Avatar answered Oct 01 '22 21:10

Dmitry Bychenko


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.

like image 25
Jakob Olsen Avatar answered Oct 01 '22 21:10

Jakob Olsen