gpt4 book ai didi

c++ - 比较两个包含浮点值的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:46 25 4
gpt4 key购买 nike

我得到两个包含 float 的字符串。我需要比较它们。我可以使用 std::string::compare 直接比较字符串吗?这是否总能给出正确的结果?我目前的方法是使用 std::stof 将字符串转换为 float ,但我更愿意避免使用 C++11 库函数。

最佳答案

在类似情况下,简单地比较字符串对您没有帮助

a = "0.43"
b = "0.4300"

如果需要比较先解析成float再比较

std::string  s1  = "0.6"
std::wstring s2 = "0.7"
float d1 = std::stof(s1);
float d2 = std::stof(s2);

然后比较它们

这是一个完整的程序

#include <iostream>   // std::cout
#include <string> // std::string, std::stof

int main ()
{
std::string s1 = "0.6"
std::wstring s2 = "0.7"
float d1 = std::stof(s1);
float d2 = std::stof(s2);

if(d1 == d2)
std::cout << "Equals!";
else
std::cout << "Not Equals!";
return 0;
}

click here for more reading on stof

关于c++ - 比较两个包含浮点值的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com