C语言 如何在C中将浮点数与整数相乘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17057679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:40:47  来源:igfitidea点击:

How to multiply float with integers in C?

cintegeroperation

提问by Wicelo

When I execute this code it returns me 1610612736

当我执行此代码时,它返回给我 1610612736

void main(){
float a=3.3f;
int b=2;
printf("%d",a*b);
}

Why and how to fix this ?

为什么以及如何解决这个问题?

edit : It's not even a matter of integer and float, if i replace int b=2: by float b=2.0f it return the same silly result

编辑:这甚至不是整数和浮点数的问题,如果我替换 int b=2: by float b=2.0f 它返回相同的愚蠢结果

回答by Carl Norum

The result of the multiplication of a floatand an intis a float. Besides that, it will get promoted to doublewhen passing to printf. You need a %a, %e, %for %gformat. The %dformat is used to print inttypes.

afloat和 an相乘的结果int是 a float。除此之外,它会double在传递给printf. 你需要一个%a%e%f%g格式。该%d格式用于打印int类型。

Editorial note: The return value of mainshould be int. Here's a fixed program:

编者按:的返回值main应该是int。这是一个固定的程序:

#include <stdio.h>

int main(void)
{
    float a = 3.3f;
    int b = 2;
    printf("%a\n", a * b);
    printf("%e\n", a * b);
    printf("%f\n", a * b);
    printf("%g\n", a * b);
    return 0;
}

and its output:

及其输出:

$ ./example 
0x1.a66666p+2
6.600000e+00
6.600000
6.6

回答by krthkr

Alternately, you could also do

或者,你也可以这样做

printf("%d\n", (int)(a*b));

and this would print the result you're (kind of) expecting.

这将打印您(有点)期望的结果。

You should always explicitly typecast the variables to match the format string, otherwise you could see some weird values printed.

您应该始终明确地对变量进行类型转换以匹配格式字符串,否则您可能会看到一些奇怪的值被打印出来。