📅  最后修改于: 2020-09-25 08:46:31             🧑  作者: Mango
double atof(const char* str);
它在
atof() 函数返回:
如果转换后的值超出范围,则将导致未定义的行为。
#include
#include
using namespace std;
int main()
{
char numberString[] = "-32.40";
double numberInDouble;
cout << "Number in String = " << numberString << endl;
numberInDouble = atof(numberString);
cout << "Number in Double = " << numberInDouble;
return 0;
}
运行该程序时,输出为:
Number in String = -32.40
Number in Double = -32.4
atof() 函数的有效浮点值包含一个可选的+或-号,后跟以下一组值:
#include
#include
using namespace std;
int main()
{
cout << "-44.01e-3" << " to Double = " << atof("-44.01e-0") << endl;
cout << "-44.01e-3" << " to Double = " << atof("-44.01e-3") << endl;
cout << "0xf1bc" << " to Double = " << atof("0xf1bc") << endl;
cout << "0xf1bc.51" << " to Double = " << atof("0xf1bc.51") << endl;
return 0;
}
运行该程序时,输出为:
-44.01e-3 to Double = -44.01
-44.01e-3 to Double = -0.04401
0xf1bc to Double = 61884
0xf1bc.51 to Double = 61884.3
#include
#include
using namespace std;
int main()
{
cout << "INFINITY" << " to Double = " << atof("INFINITY") << endl;
cout << "Inf" << " to Double = " << atof("Inf") << endl;
cout << "Nan" << " to Double = " << atof("Nan") << endl;
cout << "NAN" << " to Double = " << atof("NAN") << endl;
return 0;
}
运行该程序时,输出为:
INFINITY to Double = inf
Inf to Double = inf
Nan to Double = nan
NAN to Double = nan
通常,atof() 函数的有效浮点参数具有以下形式:
[whitespace] [- | +] [digits] [.digits] [ {e | E }[- | +]digits]
直到主非空白字符被找到ATOF() 函数将忽略所有的前导空白字符 。
然后,从该字符开始,它需要尽可能多的字符 ,以形成有效的浮点表示形式并将其转换为浮点值。最后一个有效字符之后的字符串剩余部分将被忽略,并且对结果没有任何影响。
#include
#include
using namespace std;
int main()
{
cout << "25.5" << " to Double = " << atof(" 25.5") << endl;
cout << "25.5 " << " to Double = " << atof(" 25.5 ") << endl;
cout << "25.5abcd" << " to Double = " << atof("25.5abcd") << endl;
// Returns 0 because of invalid conversion
cout << "abcd25.5" << " to Double = " << atof("abcd25.5") << endl;
// Rules for whitespace and trailing character also apply for infinity and Nan
cout << "INFINITYabcd" << " to Double = " << atof("INFINITYabcd") << endl;
cout << "INFINITY" << " to Double = " << atof(" INFINITY") << endl;
cout << "Nanlll" << " to Double = " << atof("Nanlll") << endl;
return 0;
}
运行该程序时,输出为:
25.5 to Double = 25.5
25.5 to Double = 25.5
25.5abcd to Double = 25.5
abcd25.5 to Double = 0
INFINITYabcd to Double = inf
INFINITY to Double = inf
Nanlll to Double = nan