#include<stdio.h>
#define SQR(x) x * x

int main()
{

	printf("%d", 225/SQR(15));

}

why this program outputs 225 instead of 1 (according to calculation).

Recommended Answers

All 4 Replies

this is a classic error. the macro just replaces the code in the program with your #define'd value verbatim. therefore, it's calculating according to the order of operation: 225 / 15 * 15 , which is 225.

change your #define to

#define SQR(x)     (x * x)

.

#define SQR(x)     (x * x)

Careful now... what happens if you run SQR(3+2)? (3 + 2 * 3 + 2) = 11 Every time a parameter appears in a macro, it should be surrounded by parentheses.

#define SQR(x)   ((x)*(x))
commented: well, dang. :P +7

point.

speaking of "classic errors" :$

.

just look at the maths rule BODMAS.
in your program firstly 225 is divided by 15 and after multiplyed by 15 which comes equal to 225. you should use parentheses for desired result.

commented: how about reading the thread before chirping in with an exact copy of what was already posted -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.