你能用c++再写一次吗
时间: 2024-05-24 10:11:43 浏览: 7
当然可以,以下是使用 C 语言重新编写的代码:
#include <stdio.h>
int main() {
int n, i, j;
printf("请输入一个数字:");
scanf("%d", &n);
for(i=1; i<=n; i++) {
for(j=1; j<=n-i; j++) {
printf(" ");
}
for(j=1; j<=2*i-1; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
相关问题
能用c++写一个简单的小游戏吗
当然可以!以下是一个简单的猜数字游戏的示例代码,你可以参考一下:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
// 生成随机数
srand(time(NULL));
int answer = rand() % 100 + 1;
// 游戏开始
std::cout << "欢迎来到猜数字游戏!\n";
std::cout << "系统已生成了一个 1~100 的随机数,请猜测这个数字:\n";
int guess = 0;
int count = 0;
do {
std::cin >> guess;
count++;
if (guess == answer) {
std::cout << "恭喜你,猜对了!\n";
std::cout << "你一共猜了 " << count << " 次。\n";
} else if (guess < answer) {
std::cout << "你猜的数字有点小,请再试一次:\n";
} else {
std::cout << "你猜的数字有点大,请再试一次:\n";
}
} while (guess != answer);
return 0;
}
```
运行这个程序,你可以玩一下这个猜数字游戏,看看能不能猜中答案。
可以不用vector再写一次吗?
可以的,下面是不使用vector的C++算法实现:
```C++
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=100;
int G[maxn][maxn],vis[maxn],n,m,cnt=0;//G为邻接矩阵,vis数组记录节点是否被访问,cnt记录生成树中的边数
bool is_tree=true;//标记是否为生成树
void dfs(int u,int p)//p为u的父节点
{
vis[u]=1;
for(int i=1;i<=n;i++)
{
if(G[u][i])
{
int v=i;
if(!vis[v])//如果v未被访问过,表示(u,v)为树边
{
cnt++;
dfs(v,u);
}
else if(v!=p)//如果v被访问了,并且v不是u的父节点,则表示(u,v)为回溯边
{
is_tree=false;
}
}
}
}
int main()
{
cin>>n>>m;//n为节点数,m为边数
memset(G,0,sizeof(G));
memset(vis,0,sizeof(vis));
for (int i=1;i<=m;i++)
{
int u,v;
cin>>u>>v;
G[u][v]=G[v][u]=1;//无向图,需要建立双向边
}
dfs(1,-1);//从节点1开始深度优先搜索
if(cnt!=n-1||!is_tree)//如果生成树中的边数不是n-1条,或者出现了回溯边,则不是一棵生成树
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
}
return 0;
}
```
该算法的时间复杂度为O(n^2),其中n为节点数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)