以下程序显示 double 表达式结果。
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
如何修改它以实现如下所示的效果,而无需显式定义整数、浮点或 double 类型?
编辑 实际上,我将表达式的值保存在堆栈中。所以,目前我使用的是 double 类型,因此表达式的结果是 double 类型,例如,2+2 将是 4.0 但我希望它是纯 int 2,而如果我的表达式结果是 float 则在这个我只想看到 float 结果,如 4.2+1= 5.2
我期待一些带有 union 的逻辑和一些 typedef 类型,其中我可以将 int 定义为 1,将 float 定义为 2,然后检查表达式结果当时是否是 float 的,另一方面,如果表达式结果是int 我设置类型为int
// 5+5 = 10
// 5.0+3.8 = 8.8
这是我的代码,我从用户那里获取输入并检查字符是否是数字(如果是)然后检查它是否是 float 。现在我使用 double 类型作为数字(yylval),使我的表达式能够处理用户的 float 输入,但我想要的是有一些 union 或可以检查输入表达式是否有 float 字的东西,那么答案应该是浮点否则,仅对于整数,它应该有整数结果。我没有在这里添加我的表达式评估器代码。
更新了代码语法
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);
}
最佳答案
C 没有运行时类型自省(introspection)(除了非常有限的功能,例如获取可变长度数组的大小)。在编译时,您可以使用 _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);
}
关于c - 如何在C中根据数据类型显示表达式的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52577302/