[英]Floating point in C
I am asking a user for two non-negative integer values in C. I then want to convert these to percentages (expressed as decimals). 我向用户询问C中的两个非负整数值。然后,我想将它们转换为百分比(以小数表示)。 Unfortunately, my
float
s are coming up as zeroes. 不幸的是,我的
float
变成零。 Why is this, and how do I fix it? 为什么会这样,我该如何解决?
int a = 5;
int b = 10;
int total = a + b;
float a_percent = a / total;
float b_percent = b / total;
printf("%.2f, %.2f\n", a_percent, b_percent);
You aren't using floats, you're using integers, and so the integral division gives zero (which is then assigned to a float). 您没有使用浮点数,而是使用了整数,因此整数除法给出了零( 然后将其分配给浮点数)。
To perform a floating-point operation, you must first convert the integers (or at least one of them) to a float. 要执行浮点运算,必须首先将整数(或其中至少一个)转换为浮点数。 Conveniently, we just use
total
: 方便地,我们只使用
total
:
float total = a + b; // exact
float ap = a / total;
float bp = b / total; // OK, these are now floating-point operations
除了其他人指出的问题外,该比率直到您乘以100.0才算是百分比。
An int
divided by an int
will always return an int
. 一个
int
除以一个int
将始终返回一个int
。 You'll have to make one of the two arguments a float
before dividing: 在除法之前,必须使两个参数之一成为
float
:
float a_percent = (float) a / total;
float b_percent = (float) b / total;
I am not a C expert, but my guess is because dividing an int by an int always results in an int. 我不是C专家,但是我的猜测是因为将一个整数除以一个整数总是会得到一个整数。
You may need to do something like this: 您可能需要执行以下操作:
float a_percent = (float)a/total;
float b_percent = (float)b/total;
You're first performing an integer division, then converting the result to floating point. 您首先要执行整数除法,然后将结果转换为浮点数。 This will not give the results you want.
这不会给出您想要的结果。 Either make
total
a floating point value to begin with (so that the types get automatically promoted right) or cast a
and b
to (float)
before performing the division. 在执行除法之前,要么使
total
浮点值开始(以便类型自动升为正确),要么将a
和b
为(float)
。
You are using integer math not floating point here. 您在此处使用的是整数数学而不是浮点数。 Try:
尝试:
float a_percent = a/(float)total;
float b_percent = b/(float)total;
For a simple percentage you may be happier using fixed-point. 对于一个简单的百分比,您可能会更喜欢使用定点。 Just multiply your numerator (a or b) by 100 and you'll get the percentage from the division.
只需将分子(a或b)乘以100,就可以从除法得到百分比。 forex:
外汇:
int a = 5;
int b = 10;
int total = a + b;
int a_percent = 100*a/total;
int b_percent = 100*b/total;
printf("a%%=%d, b%%=d\n", a_percent, b_percent);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.