函数不返回小数,有时是错误的值?

时间:2017-11-07 23:37:02

标签: c++ floating-point dev-c++

我正在尝试通过使用头文件中定义的函数并将斜率返回到主函数来计算用户的斜率输入。

我现在的问题是,即使我的公式是正确的,有时程序计算的斜率也是错误的。

有时,给定的斜率只是向上或向下舍入并且随机为负。我这里做错了吗?

我的主要代码:

#include <iostream>
#include "findSlope.h"
using namespace std;

int main()
{
    float p1, p2, p3, p4, rep, slope;
    int i;

    cout << "input point 1:";
    cin >> p1;
    cout << "input point 2:";
    cin >> p2;
    cout << "input point 3:";
    cin >> p3;
    cout << "input point 4:";
    cin >> p4;
    cout << "input amount of repetition:";
    cin >> rep;

    cout << "\nYour points are =" << p1 << "\t" 
        << p2 << "\t" << p3 << "\t" << p4;
    for ( i=0;i<rep;i++)
    {
        slope = findSlope(p1,p2,p3,p4,rep);
        cout << "Point 1\tPoint2\tSlope\n";
        cout << "("<<p1<<","<<p2<<")\t";
        cout << "("<<p3<<","<<p4<<")\t";
        cout << slope;
    }
    return 0;
}

我的标题文件:

#include <iostream>
using namespace std;

findSlope(float p1,float p2,float p3,float p4,float rep)
{
    float slope;

    cout << "\nInput your first coordinates (seperated by space) :";
    cin >> p1 >> p2;
    cout << "Input your second coordinates (seperated by space) :";
    cin >> p3 >> p4;

    slope = (p4-p2)/(p3-p1);

    return slope;
}

1 个答案:

答案 0 :(得分:1)

原则上,此代码不应在C ++中编译,因为您没有指定findSlope()函数的类型。

如果强制使用-fpermissive编译器标志进行编译,则该函数将为https://github.com/cancerberoSgx/jsdoc-typeof-plugin。从float到int的转换可以解释您描述的奇怪行为(在转换中溢出时截断和否定)。

尝试使用以下方法更正代码:

float findSlope(float p1,float p2,float p3,float p4,float rep)
{
    ...
}

杂项评论:

  • 您可以考虑使用double代替float。精度更高,现代CPU的开销不是很高。
  • 你在findSlope.h标题中做了两件事你不应该这样做:首先你使用一个命名空间,然后污染包括那个标题在内的所有文件;第二,你定义一个函数,这样如果你在不同的编译单元中包含相同的头,每个.cpp文件将重新编译该函数,这可能会导致链接器错误。