-3

我在面试中遇到了这个问题我不知道如何解决这个问题帮助我

“程序截断给定的浮点值(例如16.25 = 16)。您不应该将浮点值分配给整数然后将int值复制到浮点......应用不同的逻辑。”

4

3 回答 3

3

如果数字是正数:

#include <math.h>
printf("%f\n", floor(16.85));

或对于正数和负数:

printf("%f\n", trunc(16.85));
于 2013-04-30T19:17:00.777 回答
3

看看这个能不能行。

#include<stdio.h>

int main()
{

float num=16.25;
int x;
char str[10];
sprintf(str,"%f",num);
sscanf(str,"%d",&x);
printf("The number now is %d",x);
}
于 2013-04-30T19:28:53.360 回答
2

If you discard all the 'convert to string' type answers, and focus purely on mathematical operations, you could try this hideously inefficient process:

float Truncate(float n) {
  float r = 0.0
  if(n > 0.0) {
    while(n > 0.0) {
      n -= 1.0;
      r += 1.0;
    }
  } else {
    while(n < 0.0) {
      n += 1.0;
      r -= 1.0;
    }
  }
  return r;
}

It might take a hundred years to complete for larger values of N, but that's just engineering. The algorithm is sound. Actually, you could probably do something similar but with division rather than subtraction that would speed it up substantially.

于 2013-04-30T19:29:29.900 回答