【问题标题】:Code for quadratic equation gives incorrect answer二次方程的代码给出了错误的答案
【发布时间】:2013-10-15 23:58:20
【问题描述】:

您好,我是 C# 的初学者。我已经为二次方程制作了这个代码。它运行但没有给出正确的答案。

using System;
using System.Diagnostics;


namespace mynamespace
{
    class myclass
    {
        static void Main(string[] args)
        {
            float a, b, c, x1, x2;
            Console.Write("Enter Value in a");
                a=Convert.ToSingle(Console.ReadLine());
            Console.WriteLine("Enter Value in b");
                b=Convert.ToSingle(Console.ReadLine());
            Console.WriteLine("Enter Value in c");
                c=Convert.ToSingle(Console.ReadLine());

            x1=(-b + Math.Sqrt ( b*b - 4*a*c)/(2*a));
            x2=(-b - Math.Sqrt ( b*b - 4*a*c)/(2*a));
            Console.WriteLine(x1);
            Console.WriteLine(x2);
            Console.ReadKey();

                    }
    }
}

【问题讨论】:

    标签: c# math quadratic


    【解决方案1】:

    您缺少一组括号;将您的代码更改为:

    x1=((-b + Math.Sqrt ( b*b - 4*a*c))/(2*a));
    x2=((-b - Math.Sqrt ( b*b - 4*a*c))/(2*a));
    

    【讨论】:

      【解决方案2】:

      您不能将浮点数转换为字符串。你这样做:

      a = float.Parse(Console.Readline());
      

      而且你必须做一个 if 语句:

      if((b*b - 4*a*c) < 0)
      {
         Console.WriteLine("There are no real roots!");
      }
      

      然后您将其余代码放在 else 语句中。

      【讨论】:

        猜你喜欢
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多