2018年12月22日 星期六

數值分析 EX1-4

數值分析  EX1-4  P1-12   log _(e)X
n=3
xa=1.5
1.0    0.0
2.0    0.693
2.0    1.099
4.0    1.387
求 f(1.5) =  ???

n=3
xa=1.5
1.0    0.0
1.2    0.182
1.4    0.336
2.0    0.693
求 f(1.5) =  ???

/* ex1-4.c: Lagrange Interpolation Algorithm
 * Read in data file of ex1-4.dat which has n point values
 * and the value of interpolating point xa. Based on Lagrange
 * Interpolation algorithm to compute p(xa) and output its value.
 * (x[i],f[i]):given points and n+1 are number of points
 * Ln,k(x)=l=summation of (x-x[i])/(x[k]-x[i]).
 * p(x)=ff=L(x)*f(x[k])
 */











編譯及執行時 若是出現


需先將 DOS 執行的畫面  關閉





#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
   double x[30],f[30],l,ff,xa;
   int i,k,n;
 
   printf("Plaese key in n value : ");
   scanf("%d",&n);
   printf("\n");
   printf("Plaese key in xa value : ");
   scanf("%lf",&xa);
   printf("\n");
 
   printf("%d", n);
   printf("   %lf", xa);
   printf("\n");
 
   for(k=0;k<=n;k++)
   {
printf("Plaese key in x value : ");
    scanf("%lf",&x[k]);
    printf("Plaese key in y  value : ");
    scanf("%lf",&f[k]);
    printf("%lf\n", x[k]);
    printf("%lf\n", f[k]);
   }
 
 
 
   ff=0.0;
   for(k=0;k<=n;k++)
   {
      l=1.0;
      for(i=0;i<=n;i++)
      {
if(i !=k)
{
    l=l*(xa-x[i])/(x[k]-x[i]);
}
      }
      ff=ff+l*f[k];
   }
   printf("The value of p(%.4lf)=%.4lf\n",xa,ff);

//=====================================================
    printf("enter any key to exit");
fflush(stdin);
    getchar();
//=====================================================
return 0;
}



因為 scanf 本身的問題,在你的 scanf 指令成功回傳之後,你的 stdin 裡面有可能還有一些不正確的資料… 要是你不用 fflush(stdin),就直接再呼叫一次 scanf 的話,這些不正確的資料就有可能會讓 scanf 失敗,或回傳不正確的東西… 

這類的動作,就是通稱的叫作 "flush" (沖馬桶,因為動作有點像沖馬桶,把東西一路全沖到最底層的儲存的裝置,不要把這些東西暫存在中間的某個地方)… 

沒有留言:

張貼留言

2024產專班 作業2

 2024產專班 作業2   1. 系統圖       ESP32+MFRC522 組成RFID Reader 可以將RFID卡片的UID 透過 MQTT協定    上傳(發行 主題 (:topic) alex9ufo/2024/RFID/RFID_UID  ,, Payload...