Bài tập hàm trong C++ 13.05.20

/*

 Bài 1. Viết các hàm thực hiện:

 - Nhập vào ba số nguyên a, b, c thỏa mãn a>b>c>0;

 - In ra màn hình các số chẵn (nếu có)

 - Tìm ước chung lớn nhất của a, b

 */


#include <iostream>

using namespace std;

// Total declare variable

int a,b,c;

// Input a,b,c

void Input_abc(){

    cout<< "1. Input a, b, c: ";

        

    

    do{

        cout<<"\n c= ";

        cin>>c;

        if(b<=c||c<=0)

            cout<<"\n Retype n ! ";

    }while(b<=c||c<=0);

}


// Output to Screen even number

void Output_EvenNumber(){

    cout<<"\n 2. Even number: ";

    if(a%2==0)

        cout<< a<<" , ";

    if(b%2==0)

        cout<<b<<" , ";

    if(c%2==0)

        cout<<c<<" , ";

    if(a%2!=0&&b%2!=0&&c%2!=0)

        cout<<"\n No even number. ";

}

// Search Greatest common divisor

void Search_GCD(){

    while(a!=b)

    {

        if(a>b)

            a=a-b;

        else

            b=b-a;

    }

    cout<<"\n 3. Greatest common divisor of a, b: "<<a;

 

}


int main() {

    // call function

    Input_abc();

    Output_EvenNumber();

    Search_GCD();

    

    return 0;

}


-----------------------



/*


 Bài 2. Viết các hàm thực hiện:

 - Nhập từ bàn phím x, n, m (x là số thực bất kì, n, m số nguyên dương, 100>n>m)

 - Tính C(m,n) (chỉnh hợp chập m của n)

 - Tính S= x/ 1! + (x^2)/ 2! + (x^3)/ 3! ... + (x^n)/ n!

 - Kiểm tra xem m có phải là số nguyên tố không?


 */


#include <iostream>

#include <math.h>

using namespace std;

// Total declare variable

float x;

int n,m;

// Input x, n, m

void Input_(){

    cout<<"\n 1. Input  x, m, n: ";

    cout<<"\n x= ";

    cin>>x;

    

    do{

        cout<<"\n n= ";

        cin>>n;

        if(n>=100)

            cout<<"\n Retype n ! ";

    }while(n>=100);

    

    do{

        cout<<"\n m= ";

        cin>>m;

        if(n<=m)

            cout<<"\n Retype m ! ";

    }while(n<=m);

}

// Calculate Factorial

long Fac(int a){

    long f=1;

    for(int i=1;i<=a;i++)

        f=f*i;

    return f;

}

// Calculate C(m,n)

void C(int m, int n){

    cout<<"\n 2. C(m,n) = "<< Fac(n)/(Fac(m)*Fac(n-m));

}

// Calculate S = x/ 1! + (x^2)/ 2! + (x^3)/ 3! ... + (x^n)/ n!

void S(float x, int n){

    float s= 0;

    for(int i=1;i<=n;i++)

        s=s+(float)pow(x,i)/Fac(i);

    cout<<"\n 3. S = "<<s;

}

// Check prime number

void Check_prime_number(int m){

    int test=0;

    for(int i=2;i<m;i++)

        if(m%i==0){

            test=1;

            break;

        }

    cout<<"\n 3. Check prime number: ";

    if(test==0)

        cout<< m << " is prime number ! ";

    else cout<< m <<" is not prime number !";

}


// Function main


int main() {

    // call function

    Input_();

    C(m,n);

    S(x,n);

    Check_prime_number(m);

    return 0;

}


Tìm kiếm nội dung khác: