程式設計(C語言)實驗報告
實驗目的
(1)掌握函式的定義方法,呼叫方法,引數說明以及返回值;
(2)掌握實參與形參的對應關係,一集引數之間的'“值傳遞”的方式;
(3)掌握函式巢狀呼叫及遞迴呼叫的設計方法;
(4)在編寫過程中加深理解函式呼叫的程式設計思想。
實驗內容
(1)編輯,編譯,執行實驗指導中的程式,並分析輸出結果
(2)編寫一個函式primeNum(int x),功能是判別一個數是否是素數。
(3)編寫函式mulNum(int a,int b),功能是判定a是否是b的整數倍
實驗1方法一:
源程式:
#include<stdio.h>
#include<math.h>
int computeNum(int x)
{
int sum ,a,b,c,d,e;
sum=0;
x=abs(x);
a=x/10000;
b=(x%10000)/1000;
c=(x%1000)/100;
d=(x%100)/10;
e=(x%10)/1;
sum=a+b+c+d+e;
return sum;
}
main()
{
int a,b;
printf("Please input an integer:");
scanf("%d",&a);
b=computeNum(a);
printf("the sum of all digits is %dn",b);
}
輸入一個整數123 執行結果如圖
輸入整數98341驗證 執行結果如圖
方法二:
#include<stdio.h>
#include<math.h>
int computeNum(int x)
{
int sum,i,t;
sum=0;
x=abs(x);
for(i=4;i>=0;i--)
{
t=pow(10,i);
if(x>=t)
{
sum=sum+x/t;
x=x-(x/t)*t;
}
}
return sum;
}
main()
{
int a,b;
printf("Please input an integer:");
scanf("%d",&a);
b=computeNum(a);
printf("The sum of all digits is %dn:",b); }
輸入整數456執行結果如圖
輸入整數98341驗證執行結果如圖
實驗2:
源程式:
#include<stdio.h>
void move(char geton ,char puton)
{
printf("%c->%cn",geton,puton);
}
void Hanoi(int n,char one,char two,char three) {
if (n==1)
move(one,three);
else
{
Hanoi(n-1,one,three,two);
move(one,three);
Hanoi(n-1,two,one,three);
}
}
void main()
{
int m ;
printf("Input the number of diskes:"); scanf("%d",&m);
printf("The steps of moving %d diskes:n",m); Hanoi(m,'A','B','C');
}
輸入3執行結果如下:
輸入4執行結果如下:
實驗2:
源程式:
#include<stdio.h>
int i,a,x;
int primeNum(int x)
{
for(i=2;i<x;i++)
{
a=x%i;
if(a==0)
return 0;
}
return 1;
}
main()
{
printf("Please input x!n");
scanf("%d",&x);
if(x<2)
printf("wrong in put!n");
else
{
a=primeNum(x);
if(a==0)
printf("%d is not a prime number!n",x); else
printf("%d is a prime number!n",x);
}
}
輸入資料0執行結果如下:
輸入資料1執行結果如下:
輸入資料2執行結果如下:
輸入資料3執行結果如下:
輸入資料9執行結果如下:
輸入資料13執行結果如下:
輸入資料59執行結果如下:
輸入資料121執行結果如下:
實驗3: 源程式:
#include<stdio.h>
int mulNum(int a,int b) {
int i,c; c=a%b; if(c>0)
i=0; else i=1; return i; }
main() {
int a,b,s;
printf("please input a and b:n"); scanf("%d %d",&a,&b); s=mulNum(a,b); if(s==1)
printf("%d is a multiple of %dn",a,b); else
printf("%d is not a multiple of %dn",a,b); }
輸入資料1和5執行結果如下:
輸入資料5和5執行結果如下:
輸入資料6和2執行結果如下:
輸入資料6和4執行結果如下:
輸入資料20和4執行結果如下:
輸入資料37和9執行結果如下:
出現的問題及解決方法:
編譯過程中常出現因錯漏而使語句不規範的現象。解決方法:更加認真以及注意檢查。
實驗心得:
通過本次試驗我掌握了函式的定義,呼叫方法,引數的說明以及返回值,函式遞迴呼叫的設計方法等,逐步理解了函式呼叫的程式設計思想,學習過程常會遇到問題,因此需要認真理解,多作練習。