里面镶嵌名字的旋转爱心,代码实现
时间: 2023-12-05 21:29:07 浏览: 33
以下是一个在控制台中输出旋转爱心并镶嵌名字的C++代码:
```c++
#include <iostream>
#include <cmath>
#include <string>
#include <Windows.h>
using namespace std;
const double PI = 3.14159265358979323846;
int main()
{
string name = "AI";
int x = 40, y = 12, r = 10, t = 0;
while (true) {
t++;
double rad = t * PI / 180;
int nx = x + r * cos(rad);
int ny = y + r * sin(rad);
system("cls");
for (int i = 0; i <= ny; i++) {
cout << endl;
}
for (int i = 0; i < nx; i++) {
cout << " ";
}
cout << "*";
int name_x = nx - name.length() / 2;
int name_y = ny + 2;
for (int i = 0; i < name.length(); i++) {
cout << "\b \b";
}
for (int i = 0; i < name_x; i++) {
cout << " ";
}
cout << name;
Sleep(50);
}
return 0;
}
```
这个代码是在上一个例子的基础上进行了扩展,通过在旋转的爱心中镶嵌名字,增加了程序的趣味性。具体实现方法是在每次输出旋转的爱心之后,计算出名字的位置,使用`\b`控制光标位置,再输出名字。需要注意的是,因为名字的长度可能不是偶数,所以需要对位置进行适当的调整。运行这个程序,可以看到一个不断旋转的爱心中镶嵌着名字,非常有趣。