gpt4 book ai didi

c - C 中的变量替换(在变量名本身中)

转载 作者:行者123 更新时间:2023-11-30 18:21:29 25 4
gpt4 key购买 nike

我正在尝试在 C 中使用变量替换。基本上我正在尝试找到图中黑白源节点和目标节点的最短路径。这里我考虑了 5 个节点 A、B、C、D 和 E。我将节点的距离存储在 dist_a、dist_b 等数组中(我也可以将距离存储在 5x5 矩阵中)。在 for 循环中,我正在检查目标节点的直接邻居(这是用户的输入)。但是我如何替换 dstn 变量中的值,以便条件变得像 dist_e (如果用户输入 e 作为目的地)?

#include <stdio.h>
#include <conio.h>

void main()
{
int i,j;
char src, dstn, c;

int dist_a[5]={0,1,6,5,1000}; //taking 1000 as infinity means nodes aren't connected directly to each other
int dist_b[5]={1,0,1000,1,1000};
int dist_c[5]={6,1000,0,1,1};
int dist_d[5]={5,1,1,0,2};
int dist_e[5]={1000,1000,1,2,0};
clrscr();

printf("Enter source and destination\n");
scanf("%c %c",&src,&dstn);
printf("src = %c destn = %c",src,dstn);

for(i=0;i<=4;i++)
{
if(dist_dstn[i]!=0 && dist_dstn[i]!=1000) //The PROBLEM lies here. How do i substitute the value of dstn variable in the condition part.
{printf("%c updates to %d",dstn,i);}
}

getch();
}

我见过Variable Substitution in C但我认为它在这里不适用。

最佳答案

从可以在运行时检查变量名称的意义上来说,C 不是一种反射语言。

但就你而言,为什么不使用二维数组:

int dist[][5]={ 
{0,1,6,5,1000},
{1,0,1000,1,1000},
{6,1000,0,1,1},
{5,1,1,0,2},
{1000,1000,1,2,0}
};

然后,您可以通过该数组的适当索引来挑选您需要的 strip 。将 a 映射到 0,将 b 映射到 1,等等。一个 switch block 就足够了。 (不要假设 ASCII 具有华丽的 c - 'a' 类型习惯用法来表示 char c。)

关于c - C 中的变量替换(在变量名本身中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com