第四章习题
1.求最小公约数 最小公倍数 辗转相除法
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "please enter two number:";
cin >> a >> b;
int fun1(int a, int b);//函数声明
int fun2(int a, int b);//函数声明
cout << "最小公约数:" << fun1(a, b)<<endl;
cout << "最小公倍数:" << fun2(a, b)<<endl;
return 0;
}
int fun1(int a, int b)
{
//辗转相除法求最小公约数
int t,r;
if (a > b) { t = a;a = b;b = t; }//使得b是大的
while ((r=b % a )!= 0)
{
b = a;a = r;
}
return a;
}
int fun2(int a, int b)
{
int fun1(int a, int b);//函数声明
return a * b / (fun1(a, b));
}
2.求根
#include <iostream>
using namespace std;
#include <cmath>
int main() {
float a, b, c,temp;
void fun1(float a, float b, float c);//大于0
void fun2(float a, float b, float c);//等于0
void fun3(float a, float b, float c);//小于0
cout << "enter three number:";
cin >> a >> b >> c;
temp = b * b - 4 * a * c;
if (temp < 0)
fun3(a, b, c);
else if (temp == 0)
fun2(a, b, c);
else
fun1(a, b, c);
return 0;
}
void fun1(float a, float b, float c)
{
float x1, x2;
x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
cout << "x1=" << x1 << endl;
cout << "x2=" << x2 << endl;
}
void fun2(float a, float b, float c)
{
float x1, x2;
x1 =x2= (-b ) / (2 * a);
cout << "x1=" << x1 << endl;
cout << "x2=" << x2 << endl;
}
void fun3(float a, float b, float c)
{
//cout << "无解,x1和x2不存在"<< endl;
//输出虚数
float p, q;
p = - b / (2*a);
q = sqrt(4 * a * c - b * b) / (2 * a);
cout << "x1=" << p << "+" << q << "i"<<endl;
cout << "x2=" << p << "-" << q << "i"<<endl;
}
3.判断素数
#include <iostream>
using namespace std;
int main() {
int fun(int a);
int a;
cout << "enter a number:"<<endl;
cin >> a;
if (fun(a))
cout << a << "是素数" << endl;
else cout << a << "不是素数" << endl;
return 0;
}
int fun(int a)
{
int i;
for(i=2;i < a;i++)
{
if (a % i == 0) return 0;//不是素数
}
return 1;//是素数
}
5
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double e(double);
double x,sinh;
cout << "enter x :";
cin >> x;
sinh = (e(x) - e(-x)) / 2;
cout<<sinh;
return 0;
}
double e(double x)
{
return exp(x);//e的x次方
}
7.哥德巴赫猜想
#include <iostream>
using namespace std;
int main()
{
void godbaha(int n);
int prime(int n);
int n;
cout << "输入一个不小于6的偶数:"<<endl;
cin >> n;
godbaha(n);
return 0;
}
void godbaha(int n) {
int i;
int prime(int n);
for (i = 3;i < n/2;i++) {
if (prime(i))
if (prime(n - i))
cout << n << "=" << i << "+" << n - i<<endl;
}
}
int prime(int n)
{
int i;
for (i = 2;i < n;i++)
if (n % i == 0) return 0;
return 1;
}
10递归
#include <iostream>
using namespace std;
int main()
{
int n;
void converse(int n);
cout << "enetr n:" << endl;
cin >> n;
if(n<0)
{
cout << "- ";
converse(-n);
}
else converse(n);
return 0;
}
void converse(int n) {
char c;
if (n / 10 != 0)
converse(n / 10);
c = n%10 + '0';//不可以加else,否则最后一个c不经过else,就没有输出定义
cout << c<<" ";
}