#include "stdio.h" #define MAX 100 #define MAXNUM 100000 typedef struct { int n, e, weight; char vexs[MAX]; int edges[MAX][MAX]; }MGraph; void CreateMGraph(MGraph* G) { int i, j, k; int p; char ch1, ch2; int weight; printf("请输入顶点数:"); scanf_s("%d", &G->n); printf("请输入边数:"); scanf_s("%d", &G->e); printf("请输入各顶点信息(每个顶点以回车作为结束):\n"); for (i = 0; i < G->n; i++) { getchar(); printf("输入第%d个顶点:", i + 1); scanf_s("%c", &(G->vexs[i])); } for (i = 0; i < G->n; i++) for (j = 0; j < G->n; j++) G->edges[i][j] = MAXNUM; for (k = 1; k <= G->e; k++) { getchar(); printf("建立第%d条边(输入格式:顶点1,顶点2)和权值:", k); scanf_s("%c,%c,%d", &ch1,&ch2,&weight); for (p = 0; p < G->n; p++) { if (ch1 == G->vexs[p]) i = p; if (ch2 == G->vexs[p]) j= p; } G->edges[i][j] = weight; } } void CountDegree(MGraph G) { int indegree[MAX] = { 0 }, outdegree[MAX] = { 0 }; int i, j; for (i = 0; i < G.n; i++) for (j = 0; j < G.n; j++) { if (G.edges[i][j] != MAXNUM) { outdegree[i]++; indegree[j]++; } } printf("各个顶点的出度为:\n"); for (i = 0; i < G.n; i++) { printf("%c:%d\n", G.vexs[i], outdegree[i]); } printf("各个顶点的入度为:\n"); for (i = 0; i < G.n; i++) { printf("%c:%d\n", G.vexs[i], indegree[i]); } }修复数据结构代码
时间: 2024-04-27 10:23:49 浏览: 142
在输入边信息时,scanf_s函数的格式字符串中应该包含两个逗号,即"%c,%c,%d",并且在输入权值时应该使用"&"符号获取输入的值。同时,在获取顶点信息时应该使用getchar函数将回车键去掉,否则会影响后面的输入。修复后的代码如下:
#include "stdio.h"
#define MAX 100
#define MAXNUM 100000
typedef struct {
int n, e, weight;
char vexs[MAX];
int edges[MAX][MAX];
}MGraph;
void CreateMGraph(MGraph* G) {
int i, j, k;
int p;
char ch1, ch2;
int weight;
printf("请输入顶点数:");
scanf_s("%d", &G->n);
printf("请输入边数:");
scanf_s("%d", &G->e);
printf("请输入各顶点信息(每个顶点以回车作为结束):\n");
getchar();
for (i = 0; i < G->n; i++)
{
printf("输入第%d个顶点:", i + 1);
scanf_s("%c", &(G->vexs[i]));
getchar();
}
for (i = 0; i < G->n; i++)
for (j = 0; j < G->n; j++)
G->edges[i][j] = MAXNUM;
for (k = 1; k <= G->e; k++)
{
printf("建立第%d条边(输入格式:顶点1,顶点2)和权值:", k);
scanf_s("%c,%c,%d", &ch1, 1, &ch2, 1, &weight);
for (p = 0; p < G->n; p++)
{
if (ch1 == G->vexs[p])
i = p;
if (ch2 == G->vexs[p])
j = p;
}
G->edges[i][j] = weight;
}
}
void CountDegree(MGraph G) {
int indegree[MAX] = { 0 }, outdegree[MAX] = { 0 };
int i, j;
for (i = 0; i < G.n; i++)
for (j = 0; j < G.n; j++)
{
if (G.edges[i][j] != MAXNUM)
{
outdegree[i]++;
indegree[j]++;
}
}
printf("各个顶点的出度为:\n");
for (i = 0; i < G.n; i++)
{
printf("%c:%d\n", G.vexs[i], outdegree[i]);
}
printf("各个顶点的入度为:\n");
for (i = 0; i < G.n; i++)
{
printf("%c:%d\n", G.vexs[i], indegree[i]);
}
}
阅读全文