代码之家  ›  专栏  ›  技术社区  ›  ritik sharma

为什么我无法在cpp中将int类型转换为float?关闭

  •  -3
  • ritik sharma  · 技术社区  · 2 年前

    我尝试了所有其他方法来进行typecast-int-float,但我做不到…请帮忙

    #include <iostream>
    using namespace std;
    
    int main()
    {
        string s="50p";
        int a=stoi(s);
        
        float b=(float)a;
        cout<<b;
    
        return 0;
    }
    

    预期输出:

    50.00
    

    实际输出:

    50
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   wohlstad    2 年前

    在这种情况下,你的演员阵容没有问题。
    尽管在C++中,建议使用特殊的强制运算符,而且通常更安全- static_cast 在这种情况下,是在旧的C型铸造之上。
    此处提供更多信息: When should static_cast, dynamic_cast, const_cast, and reinterpret_cast be used? .

    如果要强制输出包含2位小数,则必须添加格式化语句 std::fixed , std::setprecision 要求 #include <iomanip> ):

    #include <iostream>
    #include <string>
    #include <iomanip>
    
    int main()
    {
        std::string s = "50p";
        int a = std::stoi(s);
        float b = static_cast<float>(a);
        std::cout << std::fixed;
        std::cout << std::setprecision(2);
        std::cout << b << '\n';  // newline added to make sure the terminal displays the line
    }
    

    输出

    50.00
    

    Demo

    旁注: What's the problem with "using namespace std;"?