C ++程序输出错误[重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

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

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

Input:输入的第一行包含一个整数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;

}

上述程序的输出是这个:

enter image description here

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

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

c++
1个回答
0
投票

在这段代码中:

        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";
        }

您的程序仅输入one代码块,第一个条件为true的代码块。由于您放置了else if,因此仅当else if条件为true先前条件为false时,才输入其后的程序段。

因此,您不能将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";
        }
© www.soinside.com 2019 - 2024. All rights reserved.