読者です 読者をやめる 読者になる 読者になる

個人的自由ノート

ふと自分が気になった事を書いてます

C++で問題を解く

#include <iostream>

using namespace std;

int factorial(int n){
    if(n > 0)
        return n * factorial(n - 1);
    else
        return 1;
}

int main(void){
    int in;
    cout << "整数値 : ";
    cin >> in;
    cout << factorial(in) << endl;

    return 0;
}
#include <iostream>

using namespace std;

int factorial(int n){
    int answer = 1;

    for(int i = 1; i <= n; i++){
        answer *= i;
    }

    return answer;
}

int main(void){
    int in;
    cout << "整数値 : ";
    cin >> in;
    cout << factorial(in) << endl;
    return 0;
}
#include <iostream>

using namespace std;

int gcd(int x, int y){
    if(x % y == 0) 
        return y;
    else
        return gcd(y, x % y);
}

int main(void){
    int x, y;
    cout << "2つの整数の最大公約数 : " << endl;
    cin >> x >> y;
    cout << gcd(x, y) << endl;
    return 0;
}
#include <iostream>
#include <cmath>

using namespace std;

template <class Type> Type square(Type x){
    return pow(x, 2);
}

int main(void){
    int a;
    float x;
    cout << "整数と実数を入力してください。" << endl;
    cin >> a >> x;

    cout << "aの2乗 : ";
    cout << square(a) << endl;
    cout << "xの2乗 : ";
    cout << square(x) << endl;
    return 0;
}
#include <iostream>
#include <cstring>

using namespace std;

template <class Type> Type minof(Type a, Type b){
    return a < b ? a : b;
}

template <> const char* minof<const char*>(const char* a, const char* b){
    return strcmp(a, b) < 0 ? a : b;
}

int main(void){
    int a,b;
    double x;
    char s[64], t[64];

    cout << "整数a : ";
    cin >> a;
    cout << "整数b : ";
    cin >> b;
    cout << "実数x : ";
    cin >> x;
    cout << "文字列s : ";
    cin >> s;
    cout << "文字列t : ";
    cin >> t;
    cout << minof(a, b) << endl;
    cout << minof<double>(a, x) << endl;
    cout << minof<const char*>(s, t) << endl;
    cout << minof<const char*>(s, "ABC") << endl;

    return 0;
}