0
#include <stdio.h> #include <stdlib.h> #define calc(a,b) (a*b)/(a-b) void calculate(){ int a = 20, b = 10; printf("%f\n", calc(a+4,b-2));//output 0.00000 } 

what to do to print the actual answer, 4.83.

3
  • 1
    how do you think this is 4.83? (24 * 8) / (24 - 8) = 192 / 16 = 12 Commented Aug 16, 2011 at 20:35
  • @Hunter McMillen, just execute it:) Commented Aug 16, 2011 at 20:43
  • 1
    Hunter is right. If you intentionally left out the parentheses in calc() as you wrote in another comment below, then a law should be created to forcibly keep you away from any kind of compiler ;-) Commented Aug 16, 2011 at 20:57

3 Answers 3

2
#define calc(a,b) ((a)*(b))/((a)-(b)) 

Can you spot the extra parentheses?

--> calc(a+4,b-2) resolves to ((a+4)*(b-2))/((a+4)-(b-2)). Correct.

Your solution without the extra parentheses:

--> calc(a+4,b-2) resolves to (a+4*b-2)/(a+4-b-2). Which is very different!

Sign up to request clarification or add additional context in comments.

1 Comment

Very good catch! While the integer division may cause rounding issues, the macro is definitely the real problem here. The expanded (a+4*b-2)/(a+4-b-2) isn't the same as the intended ((a+4)*(b-2))/((a+4)-(b-2))
1

The problem here is with your datatypes which are ints, not with format-specifiers. Integer division is always truncated to the whole numbers. You should consider changing your variables to float instead of int.

Try this:

#include <stdio.h> #include <stdlib.h> #define calc(a,b) (a*b)/(a-b) void calculate(){ float a = 20.0f, b = 10.0f; printf("%f\n", calc(a+4,b-2));//output 0.00000 } 

1 Comment

Or double (which, on many systems, is just as fast as float).
1

You need to fix the expression first. calc(a+4,b-2) is of type int, and integer division truncates.

For example, you could change the declarations to:

double a = 20.0, b = 10.0; 

and then change "%f\n" to "%.2f\n" to get two decimal places.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.