[英]C# Program can't view the result of triangle area using heron's formula
我一直在嘗試解決這個關於我的程序的問題,該程序使用用戶輸入的海倫公式打印三角形面積的最終結果
static void Main(string[] args)
{
//variable/s declaration
double a, b, c, Area;
//Ask for the values of the three sides of the triangle.
Console.Write("Enter first side: ");
a = double.Parse(Console.ReadLine());
Console.Write("Enter second side: ");
b = double.Parse(Console.ReadLine());
Console.Write("Enter third side: ");
c = double.Parse(Console.ReadLine());
//instantiate a triangle
Triangle KD = new Triangle();
Area =KD.FindingA();
//display the values of the three sides and the area of the triangle
Console.WriteLine("First Side = {0:R}", a);
Console.WriteLine("Second Side = {0:R}", b);
Console.WriteLine("Third Side = {0:R}", c);
Console.WriteLine("Area of triangle = {0:R}", Area);
}
public class Triangle
{
//fields
private double A, B, C, s, Area;
public double a, b, c;
//constructors
public double GetASide()
{ return this.a; }
public void SetASide(double value)
{ this.a = value; }
public double GetBSide()
{ return this.b; }
public void SetBSide(double value)
{ this.b = value; }
public double GetCSide()
{ return this.c; }
public void SetCSide(double value)
{ this.c = value; }
//create a method that will compute the area of the triangle
public double FindingA()
{
s = (a + b + c)/2;
Area = Math.Sqrt(s * (s - a) * (s - b) * (s - c));
return Area;
}
output 應該在哪里
First Side = 5.1
Second Side = 5.1
Third Side = 3.2
Area of triangle = 7.7480
但是當我輸入它時,它顯示
First Side = 5.1
Second Side = 5.1
Third Side = 3.2
Area of triangle = 0
請幫我解決這個問題,我想不出任何解決問題的辦法
您沒有正確創建三角形,三角形 class 中的a
與您的主要方法中的a
完全不同。 創建三角形后,您需要設置三角形的所有邊。
我建議定義你的三角形
public class Triangle
{
public double A {get;}
public double B {get;}
public double C {get;}
public Triangle(double a, double b, double c){
A = a; B = b; C = c;
}
public double GetArea(){
var s = (a + b + c)/2;
var area = Math.Sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
}
...
var myTriangle = new Triangle(a, b, c);
var area = myTriangle.GetArea();
這做了幾件事:
您可以選擇是否要在構造函數中預先計算面積並將其存儲在另一個 get-only 屬性中,或者按需計算,每個都有一些優點。 我傾向於按需計算,因為計算成本非常低,而且如果你存儲數百萬個三角形,memory 的成本會加起來。
如果您真的想在創建后更改三角形的邊,您可以考慮使用記錄而不是 class 因為它允許使用表達式
var myTriangle = new Triangle(3, 4, 5);
var newTriangle = myTriangle with{ A = 6 }
但是,您可以使用常規方法復制常規 class 的功能。
您在程序的主要部分中聲明和分配變量。 就像你的主程序中的 de 變量(邊 a、b 和 c)是 5.1、5.1 和 3.2。 但是您的 object 三角形 KD 中的變量仍然是空的。 function FindingA 計算 object 的邊 a、b 和 c 的面積,這些仍然是 0。希望這是一個答案。
這有效
using System;
public class Program
{
public static void Main()
{
var a = 5.1D;
var b = 5.1D;
var c = 3.2D;
var s = (a + b + c)/2.0D;
var area = Math.Sqrt(s * (s - a) * (s - b) * (s - c));
Console.WriteLine("First Side = {0:R}", a);
Console.WriteLine("Second Side = {0:R}", b);
Console.WriteLine("Third Side = {0:R}", c);
Console.WriteLine("Area of triangle = {0:R}", area);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.