PDA

View Full Version : Testing bedmas.


dE_logics
Sep21-09, 03:00 AM
In the following sources -

#include<stdio.h>
main()
{
char a = 2^2/2*2+5-1;
printf("%d \n", a);
//Expected - ((((2^2)/2)*2)+5)-1
//Expected result -- 8
//Actual result -- 4
a = 1 - 5+2*2/2^2;
printf("%d \n", a);
//Expected - ((((2^2)/2)*2)+5)-1
//Expected result -- 8
//Actual result -- -4
}

I expect a result 8 after computation of 2^2/2*2+5-1 or 1 - 5+2*2/2^2 since 1 - 5+2*2/2^2 will mean -
((((2^2)/2)*2)+5)-1 and 2^2/2*2+5-1 will mean -
((((2^2)/2)*2)+5)-1

Which yields 8.

dE_logics
Sep22-09, 02:36 AM
Sooo...is this a bug in C?

mXSCNT
Sep22-09, 04:32 PM
In C, ^ means bitwise xor, not exponentiation.

dE_logics
Sep23-09, 12:44 AM
So how do we write exponential here?

And what's the actual order then?

dE_logics
Sep24-09, 07:59 AM
aaaaa...no answers?

Mark44
Sep28-09, 06:00 PM
There is no exponent operator in C. If you want to raise a number to a power, use the standard library function pow(). For example, to calculate 22, do something like this:

#include <math.h>
.
.
.
double x;
x = pow(2.0, 2.0);

dE_logics
Oct5-09, 12:42 AM
oh...I remember that function though.

So what does exponential do?

dE_logics
Oct5-09, 12:43 AM
I mean if I've written '^' what will it mean in C?

mgb_phys
Oct5-09, 12:48 AM
Bitwise exclusive 'or' as mXSCNT said:

So take two numbers and the result number has a one bit where one and only one of the bits is on in the two numbers.

25 = 11001
12 = 01100
^. = 10101 = 21

dE_logics
Oct5-09, 06:51 AM
humm...thanks

dE_logics
Oct5-09, 07:17 AM
Ok...new issues; in this code -

#include<stdio.h>
main()
{
char a = 2/2*2+5-1;
printf("%d \n", a);
//Expected - (((2/2)*2)+5)-1
//Expected result -- 6
//Actual result -- 6
a = 1 - 5+2*2/2;
printf("%d \n", a);
//Expected -(((2/2)*2)+5)+1
//Expected result -- 6
//Actual result -- -2
}

So why does it come - 2 in the second print?

mgb_phys
Oct5-09, 09:11 AM
Order of operations:
a = 1 - 5+2*2/2;
a = 1 - 5+2*1
a = 1 - 5 + 2
a = -4 + 2 = -2

ApexOfDE
Oct5-09, 09:11 AM
char a = 2 / 2 * 2 + 5 - 1;

a = 1 - 5 + 2 * 2 / 2;

//Expected -(((2/2)*2)+5)+1



typo?
i dont get it. :(

dE_logics
Oct6-09, 12:35 AM
Yes, I got it, thanks.