如何转换 e.x。 2/3 或 1/2 输入以在 cpp 中浮动

How to Convert e.x. 2/3 or 1/2 in input to float in cpp

如何转换e.x。 2/3 或 1/2 输入以在 cpp

中浮动
string s="2/3";
float x=stod(s);

您可以尝试类似的方法:

int a,b;
string s="2/3";
sscanf(s.c_str(), "%d/%d", &a, &b);
float x = float(a)/b;

当然,您必须围绕 b 为零进行一些验证。

您可以使用 std::string::find() 找到 / 字符,然后使用 std::string::substr() 将字符串拆分为分子和分母部分。

然后使用std::stod()将每个转换为数字:

std::string numerator = s; 
std::string denominator = "1";

auto pos = s.find("/");
if (pos != std::string::npos)
{
    numerator = s.substr(0, pos);
    denominator = s.substr(pos+1);
}

double n, d;
double result = 0;
try
{
    n = std::stod(numerator);
    d = std::stod(denominator);
    if (d != 0)
    {
        result = n / d;
    }
}
catch(std::exception& ex)
{
    // parse error
}