High-level language programming-Experiment 9 Application of functions (1)

1. Training at the upper limit of the church
1. Write a function to calculate factorial *
The following program realizes reading the integer n from the keyboard, calculating and outputting n! , Please add a complete function to calculate factorial.

include "stdio.h" 
__________            
main() 
{    
	int n; 
    scanf("%d", &n); 
    printf("%ld", fanc(n)); 
} 
输入样例
3
输出样例
6
#include "stdio.h"
int fanc(int x)
{
    int i,s=1;
    for(i=1;i<=x;i++)
    {
        s=s*i;
    }
    return s;
}
main()
{
	int n;
    scanf("%d", &n);
    printf("%ld", fanc(n));
    return 0;
}

2. Variables in the function
Write the running result of the following program:

int f1(int x)
{ 	static int z=3,y=0;//注意static
  	y++;
  	z++;
  	return(x+y+z);
}
main()
{ 	int a=1,k;
  	for(k=0;k<3;k++) printf("%4d",f1(a));//注意是%4d
}

At the end of the program, please use the following program to output your answer (note the correct expression of escape characters)
#include “stdio.h”
main ()
{
printf ("_______________________");
}

Note:
static is used to describe static variables.
1. If it is defined outside the function, its effect is similar to the global variable, that is, the variable described by static can be used in the current c program file.
2. If it is defined inside the function, then this variable is only initialized once. Even if the function is called again, the static variable will not be initialized again. Therefore, the value of this variable will always be saved. The function is still the result of the last function call saved.

思路:
k=0;a=1;x=1;y=1;z=4;(x+y+z)=1+1+4=6;
k=1;a=1;x=1;y=2;z=5;(x+y+z)=1+2+5=8;
k=2;a=1;x=1;y=3;z=6;(x+y+z)=1+3+6=10;

Answer:
printf ("6 8 10");
(space space space 6 space space space 8 space space 10)

3. [Fill in the blank] Decimal number to binary number
The following program realizes that a positive integer (not more than 100000000) is input from the keyboard, and the corresponding binary number (original code) is output.
#include "stdio.h"


main ()
{
int n;
scanf ("% d", & n);
binary (n);
}
Input sample
12
Output sample
1100

Idea: Decimal to binary conversion is the remainder obtained by dividing the decimal system by 2 each time, and then displaying these remainders in reverse order.

#include "stdio.h"
int binary(int x)
{
    if(x>1)
    {
        binary(x/2);//嵌套递归
    }
    printf("%d",x%2);//递归后从后往前层层返回值
}
main()
{
    int n;
    scanf("%d", &n);
    binary(n);
}
Published 10 original articles · Like1 · Visits 190

Guess you like

Origin blog.csdn.net/weixin_39475542/article/details/105026202