2021-09-28 07:25

# float和double四舍五入问题

17140216;80.845,90.55,100.00

The each subject score of No. 17140216 is 80.85, 90.55, 100.00.

``````
#include <stdio.h>
int main()
{
int a;
double b,c,d;
scanf("%d;%lf,%lf,%lf",&a,&b,&c,&d);
printf("The each subject score of  No. %.d is %.2lf, %.2lf, %.2lf.\n",a,b,c,d);
return 0;
}

``````

• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 邀请回答

#### 3条回答默认 最新

• 赵4老师 2021-09-29 09:59
最佳回答

这个四舍五入的结果不一样，不知道和内部二进制表示有没有关系，参考下面：

``````
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void dumpdouble(double d) {
char bs[65];
char b[65];
unsigned char *p;
char e[12];
char *t;
int ex;

printf("d=%lg\n",d);
p=(unsigned char *)&d;
printf("hex=%02X %02X %02X %02X %02X %02X %02X %02X\n",p[7],p[6],p[5],p[4],p[3],p[2],p[1],p[0]);
_i64toa(*(__int64 *)&d,b,2);
sprintf(bs,"%064s",b);
printf("bin=%s\n",bs);
printf("bin=%.1s %.11s   %s\n",bs,bs+1,bs+12);
strncpy(e,bs+1,11);e[11]=0;
ex=strtol(e,&t,2);
printf("    %c %-6d-1023 1.%s\n",(bs[0]=='0')?'+':'-',ex,bs+12);
ex-=1023;
printf("    %c %-11d 1.%s\n",(bs[0]=='0')?'+':'-',ex,bs+12);
}
void dumpfloat(float f) {
char bs[65];
char b[65];
unsigned char *p;
char e[12];
char *t;
int ex;

printf("f=%g\n",f);
p=(unsigned char *)&f;
printf("hex=%02X %02X %02X %02X\n",p[3],p[2],p[1],p[0]);
ltoa(*(long *)&f,b,2);
sprintf(bs,"%032s",b);
printf("bin=%s\n",bs);
printf("bin=%.1s %.8s   %s\n",bs,bs+1,bs+9);
strncpy(e,bs+1,8);e[8]=0;
ex=strtol(e,&t,2);
printf("    %c %-4d-127 1.%s\n",(bs[0]=='0')?'+':'-',ex,bs+9);
ex-=127;
printf("    %c %-8d 1.%s\n",(bs[0]=='0')?'+':'-',ex,bs+9);
}
int main() {

double d=85.845;
printf("d(double)=%16.13lf\n",d);
printf("d(double)=%.2lf\n",d);
dumpdouble(d);

printf("\n");

float f=85.845f;
printf("f(float)=%8.5f\n",f);
printf("f(float)=%.2f\n",f);
dumpfloat(f);

return 0;
}
// d(double)=85.8450000000000
// d(double)=85.84
// d=85.845
// hex=40 55 76 14 7A E1 47 AE
// bin=0100000001010101011101100001010001111010111000010100011110101110
// bin=0 10000000101   0101011101100001010001111010111000010100011110101110
//     + 1029  -1023 1.0101011101100001010001111010111000010100011110101110
//     + 6           1.0101011101100001010001111010111000010100011110101110
//
// f(float)=85.84500
// f(float)=85.85
// f=85.845
// hex=42 AB B0 A4
// bin=01000010101010111011000010100100
// bin=0 10000101   01010111011000010100100
//     + 133 -127 1.01010111011000010100100
//     + 6        1.01010111011000010100100
//

``````
评论
解决 无用
打赏 举报