1.下列程式的功能是:利用以下所示的簡單迭代方法求方程:
cos (x) -x=0的一個實根。
xn+1=cos(xn )
迭代步驟如下:
(1)取x1初值為0.0。
(2)x0=x1,把x1的值賦給x0。
(3)x1=cos(x0),求出一個新的x1。
(4)若x0-x1的絕對值小於0.000001,執行步驟(5),否則執行步驟(2)。
(5)所求x1就是方程cos(x)-x=0的一個實根,作為函式值返回。
請編寫函式countValue ( )實現程式要求,最後呼叫函式writeDAT( )把結果輸出到檔案中。
注意:部分源程式已給出。
請勿改動主函式main()和寫函式writeDAT()的內容。
#include
#include
#include
void writeDAT();
float countValue( )
{
float x0,x1=0.0; /*定義兩個浮點型變數進行迭代*/
while(1) /*無條件迴圈*/
{
x0=x1; /*將x1賦值給x0*/
x1=cos(x0); /*求出新的x1*/
if(fabs(x0-x1)<1e-6) break; /*若x0-x1的絕對值小於0.000001,則結束迴圈*/
}
return x1; /*返回 x1的值*/
}
void main( )
{
system("CLS");
printf("實根=%fn",countValue( ));
printf("%fn",cos(countValue( ))-countValue( ));
writeDAT( );
}
void writeDAT( )
{
FILE *wf;
wf=fopen("","w");
fprintf(wf,"%fn",countValue( ));
fclose(wf);
}
2.請編寫函式void countValue(int *a,int *n),它的功能是:求出1到1000之內能被7或11整除但不能同時被7和11整除的所有整數並存放在陣列a中,並通過n返回這些數的個數。
注意:部分源程式已給出。
請勿改動主函式main()和寫函式writeDAT()的內容。
#include
#include
void writeDAT();
void countValue(int *a,int *n)
{
int i; /*定義迴圈控制變數*/
*n=0 ; /*初始化計數器變數*/
for(i=1;i<=1000;i++) /*在這個範圍內尋找符合條件的數*/
if((i%7==0 && i%11!=0)||(i%7!=0 && i%11==0))
/*如果當前的數可以被7整除而不可以被11整除,或者可以被11整除而不可以被7整除*/
{
*a=i; /*儲存符合條件的數*/
*n=*n+1; /*統計個數*/
a++;
}
}
void main()
{
int aa[1000],n,k;
system("CLS");
countValue(aa,&n);
for(k=0;k
if((k+1) %10 ==0)
{
printf("%5d",aa[k]);
printf("n");
}
else printf("%5d",aa[k]);
writeDAT();
}
void writeDAT()
{
int aa[1000],n,k;
FILE *fp;
fp=fopen("","w");
countValue(aa,&n);
for(k=0;k
if((k+1)%10==0)
{
fprintf(fp,"%5d",aa[k]);
fprintf(fp,"n");
}
else fprintf(fp,"%5d",aa[k]);
fclose(fp);
}
3.已知在檔案中存有若干個(個數<200)4位數字的正整數,函式ReadDat() 的功能是讀取這若干個正整數並存入陣列xx中。請編制函式CalValue(),其功能要求:(1)求出該檔案中共有多少個正整數totNum;(2)求這些數右移1位後,產生的新數是偶數的數的個數totCnt,以及滿足此條件的這些數(右移前的值)的算術平均值totPjz,最後呼叫函式WriteDat()把所求的結果輸出到檔案中。
注意:部分源程式已給出。
請勿改動主函式main()、讀函式ReadDat()和寫函式WriteDat()的內容。
#include
#include
#define MAXNUM 200
int xx[MAXNUM] ;
int totNum = 0 ; /* 檔案中共有多少個正整數 */
int totCnt = 0 ; /* 符合條件的正整數的個數 */
double totPjz = 0.0 ; /* 平均值 */
int ReadDat(void) ;
void Writedat(void) ;
void CalValue(void)
{
int i; /*定義迴圈控制變數*/
int data; /*用於儲存處理後產生的新數*/
for(i=0;i<200;i++) /*逐個取陣列xx中的數進行統計*/
if(xx[i]>0) /*判斷是否正整數*/
{
totNum++; /*統計正整數的個數*/
data=xx[i]>>1; /*將數右移一位*/
if(data%2==0) /*如果產生的新數是偶數*/
{
totCnt++; /*統計這些數的個數*/
totPjz+=xx[i]; /*並將滿足條件的原數求和*/
}
}
totPjz/=totCnt; /*求滿足條件的這些數(右移前的值)的算術平均值*/
}
void main()
{
int i ;
system("CLS");
for(i = 0 ; i < MAXNUM ; i++)
xx[i] = 0 ;
if (ReadDat ())
{
printf("資料檔案不能開啟!