【分享】一些經典的C/C++語言基礎演算法及程式碼(三)

weixin_33751566發表於2016-05-04

閱讀到的一些經典C/C++語言演算法及程式碼。在此分享。

簡單的四則運算計算器

這個程式小改了一點,新增了Q退出計算功能

#include <iostream>
using namespace std;

int main()
{
    float a, b;
    char chr;
    cout << "Choose operator either + or - or * or / : " << endl;
    cin >> chr;
    if(chr != 'Q')  //往復迴圈進行四則運算,若輸入Q則退出.
    {
        cout << "Enter two operands: " << endl;
        cin >> a >> b;
        switch (chr)
        {
            case '+':
                cout << a << " + " << b << " = " << a + b << endl;
                return main();
            case '-':
                cout << a << " - " << b << " = " << a - b << endl;
                return main();
            case '*':
                cout << a << " * " << b << " = " << a * b << endl;
                return main();
            case '/':
                cout << a << " * " << b << " = " << a / b << endl;
                return main();
            case 'Q':
                break;
            default:
                cout << "Error: Choose operator again! " << ends; //若有"+、-、*、/、Q"以外的輸入,則重新執行程式。
                return main();
        }
    }
    return 0;
}

檢查一個數能否分解為兩個質數的和

列舉法把一個數寫成兩個數之和,再驗證哪些加數為質數

#include <iostream>
#include <math.h>
using namespace std;

int check(int n);
int main()
{
    int i, n, flag = 0;
    cout << "Enter a positive integer: " << endl;
    cin >> n;
    for(i = 2; i <= n / 2; ++i)
    {
        if(check(i) != 0)
        {
            if(check(n - i) != 0)
            {
                cout << n << " = " << i << " + " << n - i << endl;
                flag = 1;
            }
        }
    }
    if(flag == 0)
        cout << n << " can not be expressed as sum of two prime numbers. " << endl;
    return 0;
}

//驗證加數是否為質數
int check(int n)
{
    int i, flag = 1;
    for(i = 2; i <= sqrt(n); ++i)
        if(n % i == 0)
            flag = 0;
    return flag;
}

相關文章