阅读到的一些经典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;
}
网友评论