为什么除以两个整数不会得到浮点数? [英] Why dividing two integers doesn't get a float?

查看:18
本文介绍了为什么除以两个整数不会得到浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释为什么当我将 b 除以一个整数时,它会被四舍五入,尽管它是一个浮点数?

Can anyone explain why b gets rounded off here when I divide it by an integer although it's a float?

#include <stdio.h>

void main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / 350;
    c = 750;
    d = c / 350;
    printf("%.2f %.2f", b, d);
    // output: 2.00 2.14
}

http://codepad.org/j1pckw0y

推荐答案

这是因为隐式转换.变量 b, c, dfloat 类型的.但是 / 运算符看到两个整数必须相除,因此在结果中返回一个整数,该整数通过添加小数点隐式转换为 float.如果您想要浮点除法,请尝试将两个操作数设置为 / 浮点数.如下.

This is because of implicit conversion. The variables b, c, d are of float type. But the / operator sees two integers it has to divide and hence returns an integer in the result which gets implicitly converted to a float by the addition of a decimal point. If you want float divisions, try making the two operands to the / floats. Like follows.

#include <stdio.h>

int main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / 350.0f;
    c = 750;
    d = c / 350;
    printf("%.2f %.2f", b, d);
    // output: 2.14 2.14
    return 0;
}

这篇关于为什么除以两个整数不会得到浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆