程序编译但在使用浮点时崩溃

时间:2015-02-20 23:47:27

标签: c++

所以我正在使用这个简单的代码块:

#include <iostream>
#include <cmath>

using namespace std;

int sum_of_squares (double a, double b)
{
    double sum;
    double sum1;
    sum1 = pow(a,2)+pow(b,2);
    sum = sqrt(sum1);
    return sum;
}
int main ()
{
    //User Inputs
    double x1;
    double x2;
    double y1;
    double y2;
    double r1;
    double r2;
    double diffx;
    double diffy;
    cout << "Enter the information for the first circle";
    cout << "x-coordinate:";
    cin >> x1; 
    cout << "y-coordinate:";
    cin >> y1;
    cout << "radius:";
    cin >> r1;
    cout << "Enter the information for the second circle";
    cout << "x-coordinate:";
    cin >> x2; 
    cout << "y-coordinate:";
    cin >> y2;
    cout << "radius:";
    cin >> r2;

    //Math
    double total_radius;
    double circle_sep;
    double difference;
    diffx = abs(x1-x2);
    diffy = abs(y1-y2);
    total_radius = r1+r2;
    circle_sep = sum_of_squares(diffx,diffy);
    difference = circle_sep - total_radius;

    //Outputs
    int z;
    if(total_radius>circle_sep)
        cout<< "THE CIRCLES OVERLAP.";
    else
        cout << difference;
        cout << "THE MINIMUM DISTANCE BETWEEN THE CIRCLES IS " << difference << ".";
    cout << "Enter 0 to exit";
    cin>> z;
    return 0;
}

第一个输出if语句完美地工作,即使在给出需要浮点数学的坐标时也是如此。之后的else语句也不起作用。当我删除&#34; cout&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;差异&#34;,但当我故意输入分离的圆圈时程序崩溃。如果我在那里留下那行代码,我就无法编译程序。对我来说,似乎计算机应该能够做一个简单的减法线,但它会崩溃。我有另一个类似问题的程序,我希望解决方案适用于此。

谢谢!

1 个答案:

答案 0 :(得分:0)

该程序在g ++ 4.6.3

上编译好

但是,如果您只想在THE MINIMUM DISTANCE BETWEEN THE CIRCLES IS时输出total_radius <= circle_sep消息,则应在这些缩进行周围添加花括号。