gpt4 book ai didi

c - 向此 C 计算器添加浮点模式的最简单方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:07 25 4
gpt4 key购买 nike

创建用户可以输入 'f''i' 以在整数和 float 之间切换的浮点模式的最有效方法是什么?我想这样做而不必复制 float 的整个代码。我知道类型转换是一种选择,但我不确定这是否是最安全的方式。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

int *p;
int *tos;
int *bos;

void push(int i);
int pop(void);

int main (void)
{
int a, b;
char s[80];

p = (int *) malloc(MAX*sizeof(int)); /* get stack memory */
if (!p) {
printf("Allocation Failure\n");
exit(1);
}

tos = p;
bos = p + MAX-1;

printf("\nRPN Calculator\n");
printf("Enter 'i' for integer mode\n");
printf("Enter 'f' for floating point mode\n");
printf("Enter 'q' to quit\n\n");
char *endptr;

do {
printf("> ");
scanf("%s", s);
int val = strtol(s, &endptr, 10);

if (*endptr == '\0') {
//printf("Got only the integer: %d\n", val);
}
else {
printf("operator: %s\n", endptr);
printf("integer: %d\n", val);
if (val != 0){ /* don't push val on stack if 0 */
push(val);
}
}

switch(*endptr) {
case 'i':
printf("(Integer Mode)\n");
break;
case 'f':
printf("(Floating Point Mode)\n");
break;
case '+':
a = pop();
b = pop();
// printf("%d\n",a);
// printf("%d\n",b);
// printf("%d\n",val);
printf("%d\n", a+b);
push(a+b);
break;
case '-':
a = pop();
b = pop();
printf("%d\n", b-a);
push(b-a);
break;
case '*':
a = pop();
b = pop();
printf("%d\n", a*b);
push(a*b);
break;
case '/':
a = pop();
b = pop();
if(a == 0){
printf("Cannot divide by zero\n");
break;
}
printf("%d\n", b/a);
push(b/a);
break;
case '.':
a = pop(); push(a);
printf("Current value on top of stack: %d\n", a);

break;
default:
// push(atoi(s));
push(val);
}
} while (*s != 'q'); /* Do until 'q' is entered */

return 0;
}

void push (int i) /* Put an element on the stack */
{
if (p > bos){
printf("Stack Full\n");
return;
}
*p = i;
p++;
}

int pop (void) /* Get the element from the top of the stack */
{
p--;
if(p < 0) {
printf("Stack Underflow\n");
return 0;
}
return *p;
}

最佳答案

在 C 中无法重载函数,因此无论如何您都必须复制两份。但是,您可以概括推送/弹出,以便它在具有任意数据的节点上运行。为了安全地执行此操作,您可以使用带标记的 union ,例如:

typedef struct {
enum {INT, FLOAT} type;
union {
int i;
float f;
} data;
} Node;

这还允许您在未来轻松扩展到其他数据类型。

或者你可以只使用 void* 数据,每次你想对其进行操作时不安全地转换它,傲慢地假设你总能找到你想要的(不推荐)。

关于c - 向此 C 计算器添加浮点模式的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2212291/

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