c++关于读文件时将数字字符转换为数字的问题

来源:百度知道 编辑:UC知道 时间:2024/06/03 06:13:57
主要是输出的值与期望值不一致(小数点后的位数)

#include <iostream>
using namespace std;
#include<stdio.h>
#include<cmath>
main()
{
FILE *fp;
int f=0,i=0,j=0;//记数用
char ch;
float x[20],y[20],z[20];
x[19]=0;
y[19]=0;
float X[1000],Y[1000],Z[1000];
if((fp=fopen("abc.txt","rt"))==NULL)
{
printf("\nCannot open file strike any key exit!");

}
ch=fgetc(fp);
while(ch!=EOF)
{
putchar(ch);

////////////////////////////////////////
if(ch=='X')
{ch=fgetc(fp);
putchar(ch);

for(;ch!='.';)
{
if(ch=='1'||ch=='2'||ch=='3'||ch=='4'||ch=='5'||ch=='6'||ch=='7'||ch=='8'||ch=='9'||ch=='0')
{
x[f]=ch-48;
f=f+1;
ch=fgetc(fp);
putchar(ch);
}}

没有看程序,如果你只是精度不对的话,是这样:
float pai = 3.14159265;

cout.precision(6); //保留6位有效数字
cout<<pai<<endl;
cout<<fixed<<pai<<endl; //保留小数点后6位