使用void函数的C ++数学

时间:2019-04-09 21:20:36

标签: c++

下面是我正在处理的一些代码。由于某种原因,不是从文件中读取值,而是将所有值读入0。我缺少明显的东西吗?

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>

using namespace std;

void findRadius(){
    double x1,x2,y1,y2;
    double radius = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
    cout << fixed << setprecision(2) << "The radius for the point (" << x1 <<"," << y1<<" ) and ("<<x2<<","<<y2<<") is: "<< radius <<endl;
            }
int main ()
{
    double x1;
    double x2;
    double y1;
    double y2;
    ifstream inFile;
    inFile.open("circles.txt");
        while (inFile >> x1 >> x2 >>y1 >>y2){
            findRadius();
        }

}

2 个答案:

答案 0 :(得分:2)

您根本不会将从文件中读取的值传递给函数,并且该函数正在使用从未初始化的局部变量来计算事物。

尝试以下方法:

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>

using namespace std;

void findRadius(double x1, double x2, double y1, double y2) {
    double radius = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
    cout << fixed << setprecision(2) << "The radius for the point (" << x1 << "," << y1 << " ) and (" << x2 << "," << y2 << ") is: " << radius << endl;
}

int main()
{
    double x1, x2, y1, y2;
    ifstream inFile;
    inFile.open("circles.txt");
    while (inFile >> x1 >> x2 >> y1 >> y2){
        findRadius(x1, x2, y1, y2);
    }
    return 0;
}

答案 1 :(得分:1)

  

由于某种原因,不是从文件中读取值,而是将所有值读入0。我缺少明显的东西吗?

是的,您没有将从文件中读取的值传递给函数。在该函数中,您使用的是未初始化的局部变量。

将功能更改为:

void findRadius(double x1, double x2, double y1, double y2)
{
    double radius = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
    cout << fixed << setprecision(2) << "The radius for the point (" << x1 <<"," << y1<<" ) and ("<<x2<<","<<y2<<") is: "<< radius <<endl;
}

并将其调用更改为:

while (inFile >> x1 >> x2 >>y1 >>y2){
    findRadius(x1, x2, y1, y2);
}