使用scanf()读取的符号作为C运算符 [英] Using symbols read by scanf() as C operators

查看:51
本文介绍了使用scanf()读取的符号作为C运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 scanf()中读取一个符号,然后让C将其用于它的含义.我当前的(相关)代码如下:

I want to read a symbol in from scanf() and then get C to use it for what it is. My current (relevant) piece of code looks like:

float a;     /* First Number */
char  sym;   /* Symbol (i.e. +, -, /, *) */
float b;     /* Second number.... */

puts("Please type your equation");
printf("$: ");

scanf("%f %c %f", &a, &sym, &b);

因此,如果用户键入(在 $:提示符下) 5 + 10 ,则程序应继续评估 5 + 10 但我知道我不能指望C能够做到这一点(并非先不做任何魔术工作就可以了),因为'+'只是ANSI字符代码,所以我要问的是:

So if the user were to type (at the $: prompt) 5 + 10 then the program should proceed to evaluate 5 + 10 but I know I can't expect C to do this (not without working some magic first :) because '+' is just an ANSI character code, so what I'm asking is:

如何获取C以字面意义将变量 sym 用作我们(作为人们)将其视为(加号 + )的变量,然后使用该变量像变量一样具有硬编码值来求解方程式?

How do I get C to literally take the variable sym for what we (as people) take it as (a plus +) and then use that to solve the equation as if the variables had hard-coded values?

EDIT 我现在知道这可能是不可能的(请参阅评论通过 SLaks ),因此任何变通方法都将是不错的选择!

EDIT I now understand that it may be impossible (see comment by SLaks), so any workarounds would be great!

请注意:我知道我可以使用

....
add(int a, int b)
{
        return (1 + b);
}
....
if (sym == '+') {
        add(a, b);
}

,依此类推,但是当我要包含更多的内容时,只需添加 a b (例如 a sym b sym2 c ),并且用户拥有多种类型的运算符(例如, 2 + 4-6 ),这变得很繁琐且耗时.

and so on, but when the I get to including more then just a and b (e.g. a, sym, b, sym2, c) and the user has more than a single type of operator (e.g. 2 + 4 - 6) this becomes tedious and time consuming.

推荐答案

您不能真正做到这一点.C是一种编译语言(C ++也是如此),并且您不能仅在运行时像执行C语言一样执行字符串.编译代码时会生成指令.诸如Python之类的其他可被解释的语言也支持此功能(例如Python中的 eval 函数).使用if语句可能是最有效的方法.

You can't really do that. C is a compiled language (so is C++) and you cannot just execute a string as if it is C code at run time. The instructions are generated when the code is compiled. Other languages like Python which are interpreted support this (such as the eval function in Python). Using the if statements is probably the most efficient approach.

也类似于江洁 ,我会研究反向抛光符号.这涉及使用堆栈来评估数学表达式并可以处理复杂的表达式.

Also like Jiang Jie said I would look into reverse polish notation. This involves using a stack to evaluate the mathematical expressions and can handle complex expressions.

您可能还需要研究将中缀表达式(例如 1 + 2 )转换为后缀表达式( 1 2 + ).

You will also probably need to look into converting infix expressions (e.g. 1 + 2) into postfix expressions (1 2 +).

这篇关于使用scanf()读取的符号作为C运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆