High-level language programming-experiment 9 application of functions (2)

2. Exercises under the hall
1. Definition of [Fill-in-the-blank] function
The following is a program that uses toggle division to find the greatest common divisor. Please add the definition and call of the function in the complete program, and submit the code after running.

#include  "stdio.h"
____________________
{
    int  r;
    while ((r=m%n)!=0)
    {
        m=n;
        n=r;
    }
    return  n;
}
main()
{
    int  a, b, n;
    scanf("%d%d", &a, &b);
    printf("%d\n", _______________________);
}
输入样例
24 16
输出样例
8

Idea: Toss and divide method
Insert picture description here
Answer:

#include  "stdio.h"
int abc(int m,int n){
    int  r;
    while ((r=m%n)!=0)
    {
        m=n;
        n=r;
    }
    return  n;
}
main()
{
    int  a, b, n;
    scanf("%d%d", &a, &b);
    printf("%d\n", abc(a,b));
}

2. Evaluate the function

题目:Description 输入x(x为整数),求函数值。
函数定义如下:
F(x)=x          	             x小于3
F(x)=F(x/3)*2   	             x大于等于3且x为3的倍数
F(x)=F((x-1)/3)+1   	         x大于等于3且x除3余1
F(x)=F((x-2)/3)+2   	         x大于等于3且x除3余2
输入样例
20
输出样例
6
#include<stdio.h>
 
int F(int x){
    if(x<3)
        return x;
    else if(x>=3 && x%3 == 0)
        return F(x/3)*2;
    else if(x>=3 && x%3 == 1)
        return F((x-1)/3)+1;
    else if(x>=3 && x%3 == 2)
        return F((x-2)/3)+2;
}
 
int main (){
    int a;
    scanf("%d",&a);
    printf("%d\n",F(a));
    return 0;
}
Published 10 original articles · Like1 · Visits 190

Guess you like

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