C语言 如何在整数除法中获得分数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2976011/
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 05:35:52  来源:igfitidea点击:

How to get fractions in an integer division?

cinteger-division

提问by Chad Carisch

How do you divide two integers and get a double or float answer in C?

你如何在 C 中除以两个整数并得到双精度或浮点数的答案?

回答by Mark Rushakoff

You need to cast one or the other to a floator double.

您需要将一个或另一个转换为 a floator double

int x = 1;
int y = 3;

// Before
x / y; // (0!)

// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)

Of course, make sure that you are store the resultof the division in a doubleor float! It doesn't do you any good if you store the result in another int.

当然,请确保您将除法结果存储在 a doubleor 中float!如果将结果存储在另一个int.



Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]"):

关于@Chad 的评论(“ [tailsPerField setIntValue:tailsPer]”):

Don't pass a double or float to setIntValuewhen you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.

setIntValue当您有setDoubleValue等 可用时,不要传递双精度或浮点数。这可能与我在评论中提到的问题相同,在那里您没有使用显式强制转换,并且您得到一个无效值,因为 double 被读取为 int。

For example, on my system, the file:

例如,在我的系统上,文件:

#include <stdio.h>
int main()
{
    double x = 3.14;
    printf("%d", x);
    return 0;
}

outputs:

输出:

1374389535

because the double was attempted to be read as an int.

因为试图将 double 读为 int。

回答by Pranav Totla

Use type-casting. For example,

使用类型转换。例如,

main()
    {
        float a;
        int b = 2, c = 3;
        a = (float) b / (float) c;     // This is type-casting
        printf("%f", a);
    }