开发者

Floating point in C

开发者 https://www.devze.com 2023-04-04 15:10 出处:网络
I am asking a user for two non-negative integer values in C. I then want to convert these to percentages (expressed as decimals). Unfortunately, my floats 开发者_如何学Goare coming up as zeroes. Why i

I am asking a user for two non-negative integer values in C. I then want to convert these to percentages (expressed as decimals). Unfortunately, my floats 开发者_如何学Goare coming up as zeroes. 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:

float total = a + b; // exact
float ap = a / total;
float bp = b / total; // OK, these are now floating-point operations


In addition to the problems others have pointed out, the ratio won't be a percentage until you multiply it by 100.0.


An int divided by an int will always return an int. You'll have to make one of the two arguments a float before dividing:

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.

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.


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. 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消