2016-03-03 31 views
-4

我有一些C#代碼(如下**),但我似乎無法輸出正確的答案?輸入是45(度),輸出應該是255.102(米),我的答案是錯誤的,因爲輸出讀數爲413.2653。C#編碼結構錯誤,輸入(45度)不輸出正確答案?

我必須承認,我認爲我的代碼(結構)實際上是錯誤的,而不是算術?

完整的代碼如下:

**

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace sums 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //prompt the user for angle in degrees 
      Console.Write("Enter initial angle in degrees: "); 
      float theta = float.Parse(Console.ReadLine()); 


      //convert the angle from degrees to radians 
      float DtoR = theta * ((float)Math.PI/180); 

      //Math.Cos 
      DtoR = theta * (float)Math.Cos(theta); 

      //Math.Sin 
      DtoR = theta * (float)Math.Sin(theta); 

      //t = Math.Sin/9.8 
      DtoR = theta/(float)9.8; 

      //h = Math.Sin * Math.Sin/(2 * 9.8) 
      DtoR = theta * theta/(2 * (float)9.8); 

      //dx = Math.Cos* 2 * Math.Sin/9.8 
      DtoR = theta * 2 * theta/(float)9.8; 

      //result 
      Console.Write("Horizontal distance {0} Meters. \r\n ", DtoR, theta); 
     } 
    } 
} 
+4

你知道嗎,指定'DtoR' - 五次? – Grundy

+0

您在每次計算中都覆蓋'DtoR'。 'DtoR'的值將是最後一行計算的值。 –

+0

@Green,你熟悉使用'Debugger' ..嗎?這是你可以很容易地修復以及自己找到的東西,如果你知道如何使用你可以使用的工具..請先調試你自己的代碼..你正在覆蓋你的'DtoR'現在.. – MethodMan

回答

1

好兩者的結構和算術似乎是錯誤的。

你從度轉換輸入的值,以弧度在該行:

float DtoR = theta * ((float)Math.PI/180); 

所以現在DtoR具有正確的弧度值。但是你不使用它,我們可以在該行看到:

DtoR = theta * (float)Math.Cos(theta /* <- this is wrong! */); 

Math.Cos預計弧度,但是你通過theta仍保持有度值。你也可以在以下幾行中做到這一點。

第二個問題是,你不使用任何結果! theta的值永遠不會改變,因爲您不會爲此指定任何值。您只能將值分配給DtoR,但不要使用除最後一個之外的這些值。

在最後一行中,輸出DtoR(您也可以通過theta,但它不在格式字符串中)。這是您在使用用戶輸入的原始值theta之前剛剛計算出的DtoR值。

從您的意見(代碼),我嘗試重寫代碼:

//convert the angle from degrees to radians 
float DtoR = theta * ((float)Math.PI/180); 

//Math.Cos 
float cos = (float)Math.Cos(DtoR); 

//Math.Sin 
float sin = (float)Math.Sin(DtoR); 

//t = Math.Sin/9.8 
float t = sin/(float)9.8; 

//h = Math.Sin * Math.Sin/(2 * 9.8) 
float h = sin * sin/(2 * (float)9.8); 

//dx = Math.Cos* 2 * Math.Sin/9.8 
float dx = cos * 2 * sin/(float)9.8; 

//result 
Console.Write("Horizontal distance {0} Meters. \r\n ", dx) 

注意,我只是轉換你已經做到了。在我看來,你的算法還有一些缺陷。

+0

我猜't'和'h'確實應該用來計算'dx'。 – juharr

+0

@juharr我把剩下的作爲作業,這可能是反正。他/她要求代碼問題,而不是科學。 –

相關問題