1

I implemented a squaring define directive as this :

#include <stdio.h>

#define SQR(y) ((y)*(y))

int main() {
    int a;
    printf("Enter : ");
    scanf("%d",&a);
    a = SQR(a);
    printf("The square is: %d\n",SQR(a));
    return 0;
}

But when I execute it, I don't get any error, but it is giving wrong answer every time.

Why is it giving 4th power instead of second power of input?

Cœur
  • 37,241
  • 25
  • 195
  • 267

4 Answers4

2

You are squaring it twice.

In your code:

a = SQR(a);
printf("The square is: %d\n",SQR(a));
  1. this first makes a = a*a

  2. Now you print SQR((a*a)*(a*a)), or a*a*a*a

You can replace SQR(a) in printf with a, or remove the a = SQR(a)

Try this :

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

int main() {
    int a;
    printf("Enter : ");
    scanf("%d",&a);
    printf("The square is: %d\n",SQR(a));
    return 0;
}
Max Payne
  • 2,423
  • 17
  • 32
0

Because you are writig ((a)*(a)) twice in your code.

a = SQR(a); //<-- Here a = a*a printf("The square is: %d\n",SQR(a)); //<-- and here print a*a

Vagish
  • 2,520
  • 19
  • 32
0

You calculate the square two times. You first square a here:

a = SQR(a);

and then, square this number again in the printf:

printf("The square is: %d\n",SQR(a));

Fix the problem by replacing the above printf with:

printf("The square is: %d\n", a);
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

you are misunderstanding the usage of c macro.

There is no issue with your macro definition. The issue is with the usage.

a = SQR(a);

In above line, you calculate the square of a and assign result to a again. So after above line execute the value of a is square of input value.

Then again in below line, you are calling macro on a.

printf("The square is: %d\n",SQR(a)); 

Then you prints the square of the current value of a. That value is not wt you need to get.

For example, if you input 2, you will get 16, but you need 4 as the answer.

ANjaNA
  • 1,404
  • 2
  • 16
  • 29