数据转换-坚持我的c++赋值(将字符串转换为浮点数)
data conversion - stuck with my c++ assignment (converting string to float )
我是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);
然而,我怀疑一些浮点计算的精度会有问题。
相关文章:
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数