0

我有一些代码,其中包含评估某些不等式的 if、else if 和 else 语句。
我的问题是:如何将语句的结果(在本例中为单原子、双原子、多原子)分配给字符串变量,以便稍后我可以使用此变量注释图形

/* Determine the type of gas - theoretical gamma for: 
     - monoatomic = 1.66 
     - diatomic = 1.4
     - polyatomic = 1.33 */

if (gamma <=1.36)
    printf("This gas is POLYATOMIC\n");

else if (gamma > 1.36 && gamma <= 1.5)
    printf("This gas is DIATOMIC\n");

else
    printf("This gas is MONOATOMIC\n");

如您所见,目前我只能打印出结果。但这并不能让我以后使用结果。

4

2 回答 2

2

使用变量来存储此信息:

#define POLYATOMIC 3 
#define DIATOMIC 2 
#define MONOATOMIC 1 
#define INVALID 0 

int atomicity = INVALID;
const char* gasTypeName = "ERROR";

if (gamma <=1.36)
{
    atomicity = POLYATOMIC;
    gasTypeName = "Polyatomic";
}
else if (gamma > 1.36 && gamma <= 1.5)
{
    atomicity = DIATOMIC;
    gasTypeName = "Diatomic";
}
else
{
    atomicity = MONOATOMIC;
    gasTypeName = "Monoatomic";
}

printf("The gas is %s", gasTypeName);
于 2013-03-18T18:40:35.630 回答
1

您可以将枚举用于 gastypes,将描述字符串数组用于可打印表示。将结果状态存储为整数/枚举的优点是可以很容易地进行比较,例如,在 a 中使用switch。相比之下,比较字符串有点麻烦。

这是使用X-Macros的示例实现:

#include <stdio.h>

#define GASTYPES \
    ENTRY(MONOATOMIC) \
    ENTRY(DIATOMIC) \
    ENTRY(POLYATOMIC)

typedef enum {
#define ENTRY(x) x,
    GASTYPES
#undef ENTRY
} gastype_t;

const char const * gastype_str[] = {
#define ENTRY(x) #x,
    GASTYPES
#undef ENTRY
};

int main() {
    double gamma; 
    gastype_t gastype;
    if(scanf("%lf", &gamma)) {
        if (gamma <= 1.36)
            gastype = POLYATOMIC;
        else if (gamma <= 1.5)
            gastype = DIATOMIC;
        else
            gastype = MONOATOMIC;
        printf("This gas is %s\n", gastype_str[gastype]);
        return 0;
    }
    else {
        printf("Failed to parse input :(\n");
        return -1;
    }
}

因此,在实际编译之前,预处理器将枚举和描述字符串数组的定义扩展为以下内容:

typedef enum {
    MONOATOMIC,
    DIATOMIC,
    POLYATOMIC,
} gastype_t;

const char const * gastype_str[] = {
    "MONOATOMIC",
    "DIATOMIC",
    "POLYATOMIC",
};

使用示例:

$ gcc test.c && echo "1.4" | ./a.out
This gas is DIATOMIC
于 2013-03-18T19:20:04.267 回答