[英]Evaluate an expression in C (e.g. 1+2.5*3)
This is a problem that i encountered while learning to program in c by following this book. 这是我而按照学习计划在C遇到了问题这本书。
Enter an expression : 1+2.5*3
Output: 10.5
This is what i came up with so far. 这就是我到目前为止所提出的。 EDIT
编辑
#include<stdio.h>
int main (void)
{
char c;
float f1=0.0f,f2=0.0f;
c = getchar();
while(c != '\n')
{
if(c!='+' && c!='-' && c!='*' && c!='/')
{
if (f1 == 0.0f)
{
f1 = c - '0';
c = getchar();
}
else
{
f2 = c - '0';
c = getchar();
}
}
switch (c)
{
case '+': c = getchar(); f2 = c - '0' ; f1 = f1+f2; break;
case '-': c = getchar(); f2 = c - '0' ; f1 = f1-f2; break;
case '*': c = getchar(); f2 = c - '0' ; f1 = f1*f2; break;
case '/': c = getchar(); f2 = c - '0' ; f1 = f1/f2; break;
// case '.':
default: break;
}
c = getchar();
}
printf("\n Value of the expression: %.2f", f1);
return 0;
}
The code is only implimented in assuming that all of the operands will be one digit number. 假设所有操作数都是一位数字,代码只是代表。 How do i impliment it for more than one digit/floating point number?
我如何使用多个数字/浮点数来表示它? What approach should i take to solve this problem.
我应该采取什么方法来解决这个问题。
I have no instructor to consult with(self learning & at chapter 7) and i am stuck at this for hours.So any help will be hugely appreciated. 我没有导师可以咨询(自学和第7章),我被困在这几个小时。所以任何帮助都将非常感激。
Thank You 谢谢
NB NB
someone mentioned about atoi() ... but I am looking for something else/manual 有人提到过atoi()...但我正在寻找别的东西/手册
f2 = c; // this will convert ascii charecter value of c into f2.
// How do i convert the character '2' into the digit 2 ?
This way: 这条路:
f2 = c - '0';
Characters '0'
to '9'
are guaranteed to have sequential values in C. 字符
'0'
到'9'
保证在C中具有顺序值。
If you're working in 'C', to convert a text representation of a "number" to the actual number -regardless of length- use something like atoi(). 如果你在'C'工作,要将“数字”的文本表示转换为实际数字 - 无论长度 - 使用atoi()之类的东西。 The "shortcut" that's possible when converting only one character isn't expandable or generalizable, and will have to be removed eventually.
仅转换一个字符时可能的“快捷方式”不可扩展或可推广,并且最终必须删除。 With something like atoi() on the other hand you can move from single-character numbers to multiple-character numbers without having to change any code.
另一方面,像atoi()这样的东西,您可以从单字符数字移动到多字符数字,而无需更改任何代码。
The atoi() system library code has been around for decades and completely handles all the edge cases (negative zero anyone?); atoi()系统库代码已经存在了几十年并且完全处理所有边缘情况(负零任何人?); trying to roll your own would take an awful lot of effort to produce equivalently crisp results.
试图自己动手将花费大量的精力来产生相当清晰的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.