回 帖 发 新 帖 刷新版面

主题:[讨论]看看我写的这个程序哪里有错啊

/*求方程f(x)=x3+1.1x2+0.9x-1.4=0在[0,1]区间内的实根近似解,使得误差不超过0.0001*/
using System;
namespace FcApp
{
class Class1
{
  static void Main(string[] args)
  {
   
   double y;
   double x=0.0001;
   int n=100;
   int i=0;
   double [] s=new double [n];
   do
   {
    i++;
    y=x*x*x+1.1*x*x+0.9*x-1.4;
    if(y==0)
    {
     if(x<=1&&x>=0)
      s[i]=x;
    }
    Console.WriteLine ("s[n]={0}",s[i]);
   }
   while (x>0.0001);
  }
}
}

回复列表 (共5个回复)

沙发

要看y的误差,不是x

板凳

好像思路就不对

3 楼

那要怎么解决才可以呢

4 楼

using System;

namespace 控制台程序
{
    class Class1
    {
        [STAThread]
        static void Main(string[] args)
        {
            double x,y,t1=0,t2=100;
            for(x=0;x<=1;x+=0.0001)//在[0,1]区间尝试所有的x
            {
                y=x*x*x+1.1*x*x+0.9*x-1.4;
                if(y==0)//如果有正解
                {
                    Console.Write(x);//输出正解
                    goto Finish;//结束循环
                }
                else if(Math.Abs(y)<t2)//冒泡法查找误差最小的x
                {
                    t2=Math.Abs(y);
                    t1=x;
                }
            }
            Console.WriteLine("x={0} y={1}",t1,t2);
            
            Finish:
            Console.ReadLine();
        }
    }
}

5 楼


using System;
class Class1
{
  static void Main(string[] args)
  {
   
   double y;
   double x=0.0001f;
   do
   {
    y=x*x*x+1.1*x*x+0.9*x-1.4;
    x=x+0.00001;
   } while (Math.Abs(y)>0.001);
    Console.WriteLine ("x={0}\ny={1}",x,y);
  }
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册