簡體   English   中英

為什么我的代碼總是跳過我的 c++ 的 else 語句?

[英]Why does my code keep skipping my else statement for c++?

我在學校的書中做一些編程練習,練習是關於確定用戶輸入的邊是否指示它是否是直角三角形。

要弄清楚這一點,您必須執行畢達哥拉斯定理,即 a^2 + b^2 = c^2。 我寫了一個if語句,詢問是否 (side1 * side1) + (side2 * side2) = (side3 * side3) 那么它是一個直角三角形,如果不是,我寫了一個else語句來打印它不是一個直角三角形。 下面是我寫的代碼。

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main() {
    int side1=0, side2=0, side3=0;

    cout << "Enter the first side of the triangle: " << endl;
    cin >> side1;

    cout << "Enter the second side of the triangle: " << endl;
    cin >> side2;

    cout << "Enter the third side of the triangle: " << endl;
    cin >> side3;

    if ((side1 * side1) + (side2 * side2) == side3 * side3)
    {
      cout << "It is a right angled triangle" << endl;
      exit(1);
    }

    else
    {
      cout << "It is not a right angled triangle" << endl;
      exit(1);
    }
    return 0;
}

我不斷從我的代碼中得到的響應是,一切都是直角三角形,這是我不想要的。

您應該將長度排序,因為 C 必須是勾股定理起作用的斜邊(最長邊)。 在 std::array 中收集您的整數並使用 std::sort,如下所示:

#include <iostream>
#include <string>
#include <algorithm>
#include <array>

using namespace std;

int main(){
   array<int,3> side;

   cout << "Enter the first side of the triangle: " << endl;
   cin >> side[0];

   cout << "Enter the second side of the triangle: " << endl;
   cin >> side[1];

   cout << "Enter the third side of the triangle: " << endl;
   cin >> side[2];

   std::sort( begin(side), end(side) );

   if ((side[0] * side[0]) + (side[1] * side[1]) == side[2] * side[2])
   {
      cout << "It is a right angled triangle" << endl;
   }
   else
   {
      cout << "It is not a right angled triangle" << endl;
   }
   return 0;
}

僅檢查邊 [2] 是最長的不足以確定三角形是否為直角。 您需要將等式中最長的邊放在正確的位置。

大家好,我設法讓我的代碼工作,我今天早上和我的導師談過,她說我應該為我的代碼工作的其他方面進行計算。 下面的代碼是我的固定代碼。

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

using namespace std;

int main() {

int side1 = 0, side2 = 0, side3 = 0, side = 0, sidehyp = 0;

cout << "Enter the first side of the triangle: " << endl;
cin >> side1;

cout << "Enter the second side of the triangle: " << endl;
cin >> side2;

cout << "Enter the third side of the triangle: " << endl;
cin >> side3;

side = (side1*side1) + (side2*side2);
    sidehyp = (side3*side3);


    if (side1 * side1 + side2 * side2 == side3 * side3)
    {
    cout << "It is a right angled triangle" << endl;
    }

    else if (side2 * side2 + side3 * side3 == side1 * side1)
    {
        cout << "It is a right angled triangle" << endl;
    }

    else if (side3 * side3 + side1 * side1 == side2 * side2)
    {
        cout << "It is a right angled triangle" << endl;
    }

    else
    {
        cout << "It is not a right angled triangle" << endl;
    }
return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM