C#编码结构错误,输入(45度)未输出正确答案

本文关键字:未输 输出 答案 45度 结构 编码 错误 输入 | 更新日期: 2023-09-27 18:37:17

我有一些 c# 代码(如下 **),但我似乎无法输出正确答案?输入是 45(度),输出应读取 255.102(米),我的答案是错误的,因为输出读数为 413.2653。

我必须承认,我认为我的代码(结构)实际上是错误的,而不是算术?

整个代码如下:

**

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

C#编码结构错误,输入(45度)未输出正确答案

好吧,结构和算术似乎都是错误的。

将输入的值从度数转换为该行中的弧度:

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)

请注意,我刚刚转换了您已经执行的操作。在我看来,您的算法中还有一些缺陷。