我是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]!='\0';i++)
{
p=(p*s)+(A[i]-48);
}
cout<<a+p;
getch();
return 0;发布于 2014-03-14 13:09:25
如果作业需要你演示数学,你可以使用这样的方法:
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]!='\0';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);然而,我怀疑某些浮点计算的精度会出现问题。
发布于 2014-03-14 11:04:23
您可以使用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当然,您可以将其放入函数/模板中。
https://stackoverflow.com/questions/22402781
复制相似问题