1. 使用函數(shù)計(jì)算兩點(diǎn)間的距離:給定平面任意兩點(diǎn)坐標(biāo)(x1,y1)和(x2,y2),求這兩點(diǎn)之間的距離(保留2位)小數(shù)。要求定義和調(diào)用dist(x1,y1,x2,y2)計(jì)算兩點(diǎn)間的距離。坐標(biāo)中兩點(diǎn)坐標(biāo)之間的距離公式如下:
#include <stdio.h>
#include <math.h>
double dist(x1,y1,x2,y2){
return sqrt(pow((x1-x2),2)+pow((y1-y2),2));
}
int main(){
printf("%lf\n",dist(4,7,7,11));
return 0;
}
2. 請(qǐng)編寫函數(shù)fun,它的功能是計(jì)算并輸出給定整數(shù)n的所有因子(不包括1與自身)的平方和(規(guī)定n的值不大于100)。
輸入輸出實(shí)例
Enter n:56
sum=1113
#include <stdio.h>
#include <math.h>
int fun(int n){
int i,sum=0;
if(n == 1){
return 1;
}
if(n<1 || n>100) {
printf("Error!\n");
return 0;
}
for(i=2;i<n;i++){
// 如果 n 能被 i 整除
if(!(n%i)){
sum += pow(i,2);
}
}
return sum;
}
int main(){
int n;
printf("Enter n:");
scanf("%d",&n);
printf("sum=%d\n",fun(n));
return 0;
}
3. 使用函數(shù)輸出字符矩陣:輸入矩形的長(zhǎng)度len、寬度width和字符ch,輸出一個(gè)長(zhǎng)寬分別為len和width的實(shí)心字符矩陣。要求定義并調(diào)用函數(shù)matrix(len, width, ch),實(shí)現(xiàn)在屏幕上顯示長(zhǎng)度為len、寬度為width,由字符ch組成的實(shí)心矩陣圖案。
輸入輸出實(shí)例
Enter len,width,ch:5 2 G
GGGGG
GGGGG
#include <stdio.h>
void matrix(int len,int width,char ch){
int i,j;
for(i=0;i<width;i++){
for(j=0;j<len;j++){
printf("%c",ch);
}
printf("\n");
}
}
int main(){
int len,width;
char ch;
printf("Enter len,width,ch:");
// 接收一個(gè)空格
scanf("%d%d %c",&len,&width,&ch);
matrix(len,width,ch);
return 0;
}
4. 使用函數(shù)求最大公約數(shù)和最小公倍數(shù):輸入兩個(gè)正整數(shù)m和n(0<m,n<=1000),輸出最大公約數(shù)和最小公倍數(shù)。要求定義和調(diào)用函數(shù)gcd(m,n)計(jì)算m和n的最大公約數(shù),定義和調(diào)用函數(shù)lcm(m,n)計(jì)算m和n的最小公倍數(shù)。
輸入輸出實(shí)例
Enter m,n:511 292
gcd = 73文章來源:http://www.zghlxwxcb.cn/news/detail-766589.html
lcd = 2044文章來源地址http://www.zghlxwxcb.cn/news/detail-766589.html
#include <stdio.h>
/**
* 最大公約數(shù)
*/
int gcd(int m,int n){
int c = m%n;
while(c)
{
m = n;
n = c;
c = m%n;
}
return n;
}
/**
* 最小公倍數(shù)
*/
int lcm(int m,int n){
// 選出 m 和 n 中大的一個(gè)
int c=(m>n?m:n);
while(1)
{
// 如果 c 同時(shí)能被 m 和 n 整除
if(!(c%m)&&!(c%n)){
break;
}
c++;
}
return c;
}
int main(){
int m,n;
printf("Enter m,n:");
scanf("%d%d",&m,&n);
if(m<0 || n<0 || n>1000 || m>1000 ){
printf("Error!\n");
return 0;
}
printf("gcd = %d\n",gcd(m,n));
printf("lcd = %d\n",lcm(m,n));
return 0;
}
到了這里,關(guān)于實(shí)驗(yàn)五 C語言函數(shù)程序設(shè)計(jì)習(xí)題 (使用函數(shù)計(jì)算兩點(diǎn)間的距離,請(qǐng)編寫函數(shù)fun,使用函數(shù)輸出字符矩陣,使用函數(shù)求最大公約數(shù)和最小公倍數(shù))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!