标签:默认 没有 fwrite 数值 can open inf image 浮点数
c语言向文本文件、二进制文件中写入实数。
1、
#include <stdio.h> int main(void) { FILE *fp; double pi = 3.14159265358979323846; printf("pi from value: %23.21f.\n", pi); // 因为浮点数精度有限,不能准确显示数值 if((fp = fopen("PI.txt", "w")) == NULL) printf("\aFile open failed.\n"); else { fprintf(fp, "%f", pi); // fprintf写入文件,默认保留6位有效小数 fclose(fp); } if((fp = fopen("PI.txt", "r")) == NULL) printf("\aFile open failed.\n"); else { fscanf(fp, "%lf", &pi); printf("pi from file: %23.21f.\n", pi); // double型不能准确无误的显示所有位数 fclose(fp); } return 0; }
2、
#include <stdio.h> int main(void) { FILE *fp; double pi = 3.14159265358979323846; printf("pi from value: %23.21f.\n", pi); // 因为浮点数的精度有限,与变量值不一致 if((fp = fopen("PI.bin", "w")) == NULL) printf("\aFile open failed.\n"); else { fwrite(&pi, sizeof(double), 1, fp); // 将变量pi以二进制形式写入文件 fclose(fp); } if((fp = fopen("PI.bin", "r")) == NULL) printf("\aFile open failed.\n"); else { fread(&pi, sizeof(double), 1, fp); //以二进制形式读取文件 printf("pi from file: %23.21f.\n", pi); // 显示变量,变量和写入的变量没有差异, fclose(fp); } return 0; }
标签:默认 没有 fwrite 数值 can open inf image 浮点数
原文地址:https://www.cnblogs.com/liujiaxin2018/p/14874368.html