如何得到整数除法分数? [英] How to get fractions in an integer division?
问题描述
你如何划分两个整数,并得到一张双人床或用C浮动的答案?
How do you divide two integers and get a double or float answer in C?
推荐答案
您需要转换一个或另一个到浮动
或双
。
You need to cast one or the other to a float
or double
.
int x = 1;
int y = 3;
// Before
x / y; // (0!)
// After
((double)x) / y; // (0.33333...)
x / ((double)y); // (0.33333...)
当然,请确保你存储的结果的在双击
或浮动师<的/ code>!它不会给你带来任何好,如果你将结果存储在另一个
INT
。
关于@乍得的评论( [tailsPerField setIntValue:tailsPer]
):
Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]
"):
不传一张双人床或浮到<一个href=\"http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSControl/setIntValue%3a\"><$c$c>setIntValue$c$c>当你有<一个href=\"http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSControl_Class/Reference/Reference.html#//apple_ref/occ/instm/NSControl/setDoubleValue%3a\"><$c$c>setDoubleValue$c$c>,等可用。这可能是同样的问题,因为我的评论,在这里你没有使用显式类型转换所提到的,因为双被读为int你得到一个无效的值。
Don't pass a double or float to setIntValue
when 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.
例如,我的系统上,该文件:
For example, on my system, the file:
#include <stdio.h>
int main()
{
double x = 3.14;
printf("%d", x);
return 0;
}
输出:
1374389535
因为双试图被解读为一个int。
because the double was attempted to be read as an int.
这篇关于如何得到整数除法分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!