这是我学习C++时自己平常练习过的代码,大家也可尝试自己敲一遍,运行看看结果。
1、心形方程
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float x, y;
for (y = 1.5f; y > -1.5; y -= 0.1f)
{
for (x = -1.5f; x < 1.5f; x += 0.05f)
{
float a = x * x + y * y - 1;
if ((a * a * a - x * x * y * y * y) < 0)
cout << 'x';
else
cout << " ";
}
cout << endl;
}
}
运行结果如图:
2、 猜数字游戏
#include <iostream>
#include<ctime>
using namespace std;
int main()
{
//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都一样
srand((unsigned int)time(NULL));
//1、系统生成随机数
int num = rand() % 100 + 1;
//2、玩家进行猜测
int val = 0; //玩家输入的数据
int t = 0; //循环次数
//3、判断玩家的猜测
cout << "请输入您猜测的数字:" << endl;
while (1)
{
cin >> val;
if (val > num)
cout << "猜测过大" << endl;
else if (val < num)
cout << "猜测过小" << endl;
else
{
cout << "恭喜您猜对了!" << endl;
break;
}
t++;
if (t == 7)
{
cout << "很抱歉,挑战失败!" << endl;
break;
}
}
}
3、一元二次方程求解
#include<iostream>
#include <math.h>
using namespace std;
int main()
{
double a, b, c, s, s1, x1, x2; //a,b,c分别是二次方程的二次项系数、一次项系数和常数,s为判别式中的Δ,s1为Δ的平方根
//让用户输入数值
cout << "请输入二次项系数:" << endl;
cin >> a;
cout << "请输入一次项系数:" << endl;
cin >> b;
cout << "请输入常数项:" << endl;
cin >> c;
s = b * b - (4 * a * c);
s1 = pow(s, 0.5); //使用pow函数来开平方,即0.5次方,注意使用pow函数时头文件要包含<math.h>
cout << fixed;
cout.precision(6); //上面两行是由于题目要求限制输出小数时的位数,可略去
if (a == 0 && b == 0) //情形一:当a,b都为0时,原方程必然无解,或者说根本不成立
cout << "error" << endl;
else if (a == 0) //情形二:只有a为0时,原方程即为一元一次方程
{
x1 = -c / b;
cout << "x1 = " << x1 << endl; //一元一次方程只有一解
}
else if (s < 0) //情形三:a,b都不为0,则采用判别式来判别是否有根存在,此时Δ小于0,原方程无实数根
cout << "error" << endl;
else if (s == 0) //情形四:此时Δ等于0,原方程有两个实数根,且为重根
{
x1 = -b / (2 * a);
cout << "x1 = " << x1 << endl;;
}
else if (s > 0) //情形五:此时Δ大于0,原方程有两个不相等的实数根
{
x1 = (-b + s1) / (2 * a);
x2 = (-b - s1) / (2 * a);
cout << "x1 = " << x1 << "\t" << "x2 = " << x2 << endl;
}
else
cout << "error" << endl;
}
以x²+5x+4 = 0为例,运行结果如下: