首页 > 解决方案 > C++ 程序给出错误的输出

问题描述

我正在尝试使用 C++ 解决一个简单的问题。问题陈述是这样的:

给出了 N 个三角形。每个三角形由其三个角在二维笛卡尔平面中的坐标标识。工作是找出给定三角形中有多少是直角三角形。直角三角形是其中一个角是 90 度角的三角形。三角形的顶点具有整数坐标,并且所有给定的三角形都是有效的(三个点不共线)。

输入:输入的第一行包含一个整数 N,表示三角形的数量。以下 N 行中的每一行都包含六个空格分隔的整数 x1 y1 x2 y2 x3 y3,其中 (x1, y1)、(x2, y2) 和 (x3, y3) 是三角形的顶点。

输出:输出一个整数,即给定三角形中直角三角形的个数。

我的 C++ 程序是这样的:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;

    cout<<"\n";

    int ans = 0;
    for(int i=0;i<n;i++)
    {
        int x1,y1,x2,y2,x3,y3;
        cin>>x1>>y1>>x2>>y2>>x3>>y3;

        double side1 = (double)sqrt( ( (x1-x2) * (x1-x2) ) + ( (y1-y2) * (y1-y2) ) );
        double side2 = (double)sqrt( ( (x2-x3) * (x2-x3) ) + ( (y2-y3) * (y2-y3) ) );
        double side3 = (double)sqrt( ( (x1-x3) * (x1-x3) ) + ( (y1-y3) * (y1-y3) ) );

        double A = side1 * side1;
        double B = side2 * side2;
        double C = side3 * side3;

        cout<<"A = "<<A<<"  B = "<<B<<"  C = "<<C<<"\n";

        cout<<"A+B = "<<A+B<<" , ";
        cout<<"B+C = "<<B+C<<" , ";
        cout<<"A+C = "<<A+C;

        cout<<"\n";

        if( (A + B) == C )
        {
            ans++;
            cout<<"first\n";
        }
        else if( (B + C) == A )
        {
            ans++;
            cout<<"second\n";
        }
        else if( (A + C) == B )
        {
            ans++;
            cout<<"third\n";
        }

        cout<<"\n\n";
    }

    cout<<"ans = "<<ans;

}

上述程序的输出是这样的:

在此处输入图像描述

但是正确的输出应该是 ans = 3 ,因为输入示例的第一个三角形和最后两个三角形是直角三角形。

我不明白为什么我的程序给出了错误的输出。

标签: c++

解决方案


在这段代码中:

        if( (A + B) == C )
        {
            ans++;
            cout<<"first\n";
        }
        else if( (B + C) == A )
        {
            ans++;
            cout<<"second\n";
        }
        else if( (A + C) == B )
        {
            ans++;
            cout<<"third\n";
        }

你的程序只输入一个代码块,第一个条件是true. 既然你放else if了,它后面的块只会在条件为时输入else iftrue一个条件为

因此,您的增量永远不会ans超过 1。

要解决此问题,您可以执行以下任一操作:

        if( (A + B) == C )
        {
            ans++;
            cout<<"first\n";
        }

        if( (B + C) == A )
        {
            ans++;
            cout<<"second\n";
        }

        if( (A + C) == B )
        {
            ans++;
            cout<<"third\n";
        }

仅当一次可以满足多个条件时才有效,或者:

        if( (A + B) == C )
        {
            ans = 1;
            cout<<"first\n";
        }
        else if( (B + C) == A )
        {
            ans = 2;
            cout<<"second\n";
        }
        else if( (A + C) == B )
        {
            ans = 3;
            cout<<"third\n";
        }

推荐阅读