如何将变量类型整数转换为double

时间:2015-02-03 10:48:42

标签: type-conversion

我想在下面的代码中将整数转换为double:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int a , b;
    double c;
    cout<<"Enter two integers: ";
    cin>>a>>b;
    try
    {
        if (b == 0)
            throw 0;
    }
    catch (int a)
    {
        cout<<"You made a division by zero?"<<endl<<a;
    }
    c = static_cast<double>(a/b);
    cout<<"The division  is: "<<fixed<<setprecision(2)<<c;

}

如何更改代码以输出double值?

2 个答案:

答案 0 :(得分:0)

如上所述,你应该投射不是除法的结果而是变量本身,以获得双倍的价值。这三个选项都有效。

int a, b;
    double c;
    std::cout << "Enter two integers: ";
    std::cin >> a >> b;
    try
    {
        if (b == 0)
            throw 0;
    }
    catch (int a)
    {
        std::cout << "You made a division by zero?" << std::endl << a;
    }
    c = static_cast<double>(a) / b;
    c = a / static_cast<double>(b);
    c = static_cast<double>(a) / static_cast<double>(b);

    std::cout << "The division  is: " << std::fixed << std::setprecision(2) << c;
    std::cin >> a >> b;

答案 1 :(得分:0)

你正在施放分裂的结果,你应该转换操作数。

不要使用异常来捕获您使用简单if捕获的条件。只需使用if,如果第二个操作数为零,则使用else跳过除法。

int a , b;
double c;
cout<<"Enter two integers: ";
cin>>a>>b;
if (b == 0) {
  cout<<"You made a division by zero?"<<endl;
} else {
  c = static_cast<double>(a) / static_cast<double>(b);
  cout<<"The division  is: "<<fixed<<setprecision(2)<<c;
}
相关问题