第一题,输入3个数,求最大值
#include<iostream>
using namespace std;
int max(int, int, int);
int main()
{
int a,b,c;
cin >> a>>b>>c;
int max1 = max(a,b,c);
cout << max1 << endl;
}
int max(int a,int b,int c)
{
int max=0;
if (a > b)
{
if (a > c)
max = a;
else
max = c;
}
else
{
if (b > c)
max = b;
else
max = c;
}
return max;
}
我当初想到就是这样操作,没想到让max=a,如果想到这个,就可以减少不少代码量。 还用数组的方法输入输出试了下也可以。
第二题,求方程ax2+bx+c=0的根
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double a, b, c;
cout << "please enter three number :" << endl;
cin >> a >> b >> c;
printf("The original equation is:%f*x^2+%f*x+%f=0\n", a, b, c);
if (b * b - 4 * a * c >= 0)
{
double root1=0, root2=0;
root1 = (-b + sqrt(b * b - 4 * a * c) )/ (2 * a);
root2 = (-b - sqrt(b * b - 4 * a * c) )/ (2 * a);
cout << "The two solutions to this equation are " << root1 << " and " << root2 << endl;
}
else
{
cout << "There is no solution to this equation." << endl;
}
}
考虑得不够全面,还有几种情况漏掉了。只考虑了一定为一元二次的方程情况。 其中还用了C语言的printf(),因为我感觉用cout输出跟printf()相同的效果比较麻烦,反正C语言语法在c++里面也不违法,我就这样用了。不过不是个好做法。
2022年10月14日00:30:40