数据转换-坚持我的c++赋值(将字符串转换为浮点数)

data conversion - stuck with my c++ assignment (converting string to float )

本文关键字:转换 字符串 浮点数 赋值 坚持 我的 c++ 数据      更新时间:2023-10-16

我是c++的新手,我正试图编写代码将字符串转换为浮点数(我不应该使用atof),但我的代码输出是0。请帮助我了解问题所在:

char A[10];
int N[10],c,b=10,a=0,p=0,i;
float s=0.1;
cout<<"reshte ra vared namaeed:";
cin>>A;

for( i=0;A[i]=!'.';i++)
{
a=(a*b)+(A[i]-48);

}

for(A[i]=='.';A[i]!='';i++)
{
p=(p*s)+(A[i]-48);

}
cout<<a+p;

getch();
return 0;

可以使用StringStream。

#include <iostream>
#include <string>
#include <sstream>

你可以很容易地使用它。例如:

stringstream sstr;
string s;
float f;
cin >> s; // Get input from stdin
sstr << s; // Copy string into stringstream
sstr >> f; // Copy content of stringstream into float
cout << f << endl; // Output your float

当然你可以把它放到函数/模板中

如果作业需要你演示数学,你可以这样写:

char A[10];    
int f1=0;
int dot_index=0;
cout << "Enter a floating point number:" << endl;
cin>>A;
for(int i=0; A[i]!='.'; i++)
{            
    f1= ( f1*10 ) + ( A[i]-48 );       
    dot_index=i+1; //we will stop 1 char before '.'
}
float f2=0;
int count=1;
for(int i=dot_index+1;A[i]!='';i++)
{
    float temp1 = static_cast<float>(A[i]-48);
    float temp2 = pow(10,count);       
    f2+= temp1/temp2;                
    count++; 
}
float f = f1 + f2;
cout<< " float : " << f1 << "+" << f2 << " = " << f << endl;
printf("n float %.10f",f);

然而,我怀疑一些浮点计算的精度会有问题。