首页 > 解决方案 > 如何根据 C 中的数据类型显示表达式的结果

问题描述

以下程序显示双重表达式结果。

int main()
{
double a=5,b=10, sum; //I have to declare the types as double so I get the result in double, What I want is some way to get a floating sum when floats are added and int when ints are added (like expect 5+10 to be 15 not 15.00000)

sum = a+b;

printf("the sum is %lf \n", sum);

return 0; 
}
// the sum is 15.000000

在不明确定义整数、浮点或双精度类型的情况下,如何修改它以实现如下所示?

编辑实际上,我将表达式的值保存在堆栈中。所以,目前我使用的是双精度类型,所以表达式的结果是双精度类型,例如,2+2 将是 4.0,但我希望它是纯 int 2,而如果我的表达式结果是浮点数,那么在这个案例我只想看到像 4.2+1= 5.2 这样的浮动结果

我期待一些带有联合的逻辑和一些 typedef 类型,我可以将 int 定义为 1 并将 float 定义为 2,然后检查表达式结果是否是浮动的,另一方面,如果表达式结果是,我将结果类型设置为 float int 我将类型设置为 int

// 5+5 = 10
// 5.0+3.8 = 8.8 

这是我的代码,我从用户那里获取输入并检查字符是否为数字,如果是,则检查它是否为浮点数。现在我对数字(yylval)使用双精度类型来使我的表达式与用户的浮动输入一起工作,但我想要的是有一些联合或可以检查输入表达式是否有浮点数的东西,那么答案应该是浮点数否则只有整数它应该有整数结果。我没有在这里添加我的表达式评估器代码。

更新了代码语法

while (ch==' '||ch=='\t'||ch=='\n') ch=getchar();

if (isdigit(ch)) {
    do {
        yytext[i]=ch;
        yylval=atoi(yytext);
        num = num * 10;
        num = num + yylval - '\0';

        ch=getchar();
    } while (isdigit(ch));
    yytext[i]=0;

if (ch == '.')
{
    ch=getchar();
    double weight;
    weight =1;
    while (isdigit(ch))
    {
        weight = weight / 10;
        double scaled;
        yytext[i]=ch;
        yylval=atoi(yytext);

        scaled = yylval  * weight;
        printf("scaled value in loop is %lf\n", scaled);
        num = num + scaled;
        ch=getchar();
    }
    yytext[i]=0;
}
yylval = num;

return(NUMBER); 
}

标签: ctypes

解决方案


C 没有运行时类型自省(除了非常有限的功能,例如获取可变长度数组的大小)。在编译时,您可以使用以下命令在类型之间进行选择_Generic

#define Print(x)    \
    printf(_Generic((x),    \
            float        : "%g\n",  \
            double       : "%g\n",  \
            int          : "%d\n",  \
            unsigned int : "%u\n",  \
            long int     : "%ld\n"  \
        ), (x))


#include <stdio.h>


int main(void)
{
    Print(3u);
    Print(-4);
    Print(7.2f);
    Print(3 + 4.5);
}

推荐阅读