當前位置:編程學習大全網 - 編程語言 - 計算物理編程求解啊

計算物理編程求解啊

#include<stdio.h>

#include<stdlib.h>

#include<iostream.h>

typedef struct data

{

float x;

float y;

}Data;//變量x和函數值y的結構

Data d[20];//最多二十組數據

float f(int s,int t)//牛頓插值法,用以返回插商

{

if(t==s+1)

return (d[t].y-d[s].y)/(d[t].x-d[s].x);

else

return (f(s+1,t)-f(s,t-1))/(d[t].x-d[s].x);

}

float Newton(float x,int count)

{

int n;

while(1)

{

cout<<"請輸入n值(即n次插值):";//獲得插值次數

cin>>n;

if(n<=count-1)// 插值次數不得大於count-1次

break;

else

system("cls");

}

//初始化t,y,yt。

float t=1.0;

float y=d[0].y;

float yt=0.0;

//計算y值

for(int j=1;j<=n;j++)

{

t=(x-d[j-1].x)*t;

yt=f(0,j)*t;

//cout<<f(0,j)<<endl;

y=y+yt;

}

return y;

}

float lagrange(float x,int count)

{

float y=0.0;

for(int k=0;k<count;k++)//這兒默認為count-1次插值

{

float p=1.0;//初始化p

for(int j=0;j<count;j++)

{//計算p的值

if(k==j)continue;//判斷是否為同壹個數

p=p*(x-d[j].x)/(d[k].x-d[j].x);

}

y=y+p*d[k].y;//求和

}

return y;//返回y的值

}

void main()

{

float x,y;

int count;

while(1)

{

cout<<"請輸入x[i],y[i]的組數,不得超過20組:";//要求用戶輸入數據組數

cin>>count;

if(count<=20)

break;//檢查輸入的是否合法

system("cls");

}

//獲得各組數據

for(int i=0;i<count;i++)

{

cout<<"請輸入第"<<i+1<<"組x的值:";

cin>>d[i].x;

cout<<"請輸入第"<<i+1<<"組y的值:";

cin>>d[i].y;

system("cls");

}

cout<<"請輸入x的值:";//獲得變量x的值

cin>>x;

while(1)

{

int choice=3;

cout<<"請您選擇使用哪種插值法計算:"<<endl;

cout<<" (0):退出"<<endl;

cout<<" (1):Lagrange"<<endl;

cout<<" (2):Newton"<<endl;

cout<<"輸入妳的選擇:";

cin>>choice;//取得用戶的選擇項

if(choice==2)

{

cout<<"妳選擇了牛頓插值計算方法,其結果為:";

y=Newton(x,count);break;//調用相應的處理函數

}

if(choice==1)

{

cout<<"妳選擇了拉格朗日插值計算方法,其結果為:";

y=lagrange(x,count);break;//調用相應的處理函數

}

if(choice==0)

break;

system("cls");

cout<<"輸入錯誤!!!!"<<endl;

}

cout<<x<<" , "<<y<<endl;//輸出最終結果

}

  • 上一篇:求助求助,貓咪拉肚子了 還呈噴射狀
  • 下一篇:怎麽賺外快
  • copyright 2024編程學習大全網