簡體   English   中英

堅持我的c ++任務(將字符串轉換為float)

[英]stuck with my c++ assignment (converting string to float )

我是c ++的新手,我正在嘗試編寫一個代碼來將字符串轉換為float(我不應該使用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;

您可以使用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]!='\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);

但是我懷疑某些浮點計算的精度會出現問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM