使用int和输出浮点数计算?

时间:2016-09-08 13:47:16

标签: c++

//findSlope(twoPoints).exe
//finding the slope of line AB, using coordiantes of point A and B.

#include <iostream>

int main()
{
    int a, b, c, d;
    float answer;

    std::cout << "The X coordiante of A: ";
    std::cin >> a;
    std::cout << "\nThe Y coordiante of A: ";
    std::cin >> b;
    std::cout << "\nThe X coordiante of B: ";
    std::cin >> c;
    std::cout << "\nThe Y coordiante of B: ";
    std::cin >> d;
    std::cout << "\nThe slope of line AB = " << std::endl;

    answer = (b-d)/(a-c); 

    std::cout.setf(std::ios::fixed);
    std::cout.precision(3);

    std::cout << answer << std::endl; 
    //alternative= std::cout << fixed << setprecision(#) << answer << std::endl;

    std::cout.unsetf(std::ios::fixed);

    return 0;
}

我正在学习C ++,我尝试编写一个程序,使用两点坐标计算斜率。

我理解如果我将float用于我为坐标声明的变量,则计算结果将输出为带有小数的float。但是,我想知道我是否仍然可以使用int进行用户输入,这样我就可以确保输入是整数。

额外问题:是否可以将以“#。##”形式呈现的float转换为“## /#”?更像是我们如何做数学IRL。

2 个答案:

答案 0 :(得分:2)

您可以使用implicit conversion加倍:

answer = (b-d)/(a-c*1.0); 

explicit cast

answer = (b-d)/(a-(float)c); 

奖金:

答案 1 :(得分:-1)

您可以使用int进行用户输入,但要精确计算包含除法运算符/的任何内容,您需要转换为浮点类型。

通常认为在C ++中使用static_cast是一种很好的做法(尽管你仍然可以使用c风格的(float)语法)。

例如:

answer = static_cast<float>(b - d) / (a - c);

在此,您将(b - d)转换为float然后将其除以整数,从而产生float

请注意,以下内容无法正常运行:

answer = static_cast<float>((b - d) / (a - c));

原因是您首先int除以另一个int然后将结果int转换为float

P上。 S. float 真的不准确,所以我建议在所有情况下都使用double而不是float,除非你想写更快的代码取决于数学的准确性(即使我不确定它在现代处理器上会更快)或保持与使用float的某些功能的现有库的兼容性。