本帖最后由 for 于 2018-1-26 13:49 编辑
练习1
求一个数的平方根
#include<stdio.h>
#include<math.h>//由于sqrt函数在math.h的头文件背所以需要include
int main()
{
int n;
printf("n=");
scanf("%d",&n);
printf("%f\n",sqrt(n));/*n是一个整数,最终印出来的结果是一个浮点数
在这里n进行了一次隐性转型*/
return 0;
}
练习2
生成随机数的练习
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(0));
int i;
for(i=1;i<=5;i++,printf("%d\n",rand()));
return 0;
}
/*rand的函数为
int rand(void)是没有参数的函数
虽然引用rand生成的数是随机的,但是已经编号的程序每次打开都是一样的数
所以这里用到srand是rand的参数种,
srand的中的参数是rand的随机生成数的第一个数字
这里应用time函数是为了让生成数每秒都在变化
*/
练习3
丢骰子练习
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(0));
int i;
/*for(i=1;i<=5;i++){
int dice;
do{
dice=rand();//rand是随机在0到任何数之间,这样写程序虽然行得通但是效率太低,于是有了下面的写法
}while(dice<1||dice>6);
printf("%d\n",dice);
}*/
for(i=1;i<=5;i++){
int dice=rand()%6+1;//把所有数都对六取余数,就变成0-5之间,再加1
printf("%d\n",dice);
}
return 0;
}
函数返回
函数是可以调用自身的,只要在一开始的时候进行了声明就可以使用
如:
void f(void)
int main()
{
f();
return 0;
}
void f(void){
f();
}
这个程序在执行的过程中从main开始呼叫f函数
f函数里面再次呼叫f函数
就会有很多个f函数在运行,并且一直增加
然后程序可能会被迫结束
这是个不合法的程序
练习4
数数字的练习(使用函数返回)
#include<stdio.h>
void count(int);
int main()
{
count(1);
return 0;
}
void count(int i){
if(i<=3){
count(i+1);
printf("%d\n",i);/*如果想印123,可以将if中的两条指令换一下位置*/
}
}
这个程序从main开始执行,先运行count(1)调用函数count
然后被调用的count中还有count,于是继续调用count,不过此时的count是一个新的count
与之前调用的count不是同一个
有点像是一个for语句中嵌套着一个for
这个程序count一共被调用了4次,然后逐一返回前一个的count
至于这个函数为什么没有return,是因为这个函数是一个空返回值的函数,也就是以return;返回,并且return;是可以省略的
练习5
求连续整数的和(函数返回)
#include<stdio.h>
int sum(int);
int main()
{
int N;
printf("N=");
scanf("%d",&N);
printf("sum is %d\n",sum(N));
return 0;
}
int sum(int N){
if(N==1){
return 1;
}
return sum(N-1)+N;
}
练习6
爬楼梯方法总数练习
题目是这样的,一步只能走1阶或2阶的楼梯问第n阶有几种走法
也叫斐波切纳数列
#include<stdio.h>
int total(int N);
int main()
{
int N;
printf("N=");
scanf("%d",&N);
printf("共有%d种走法\n",total(N));
return 0;
}
int total(int N){
if(N<=2){
return N;
}
return total(N-1)+total(N-2);
}
|