开发者

Which Format Specifier

#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));//outp开发者_如何学Cut 0.00000
}

what to do to print the actual answer, 4.83.


#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!


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜