黑莓计算器

时间:2014-02-12 08:13:10

标签: java blackberry java-me

您好我正在研究计算器,但我没有得到正确的输出。例如

4+(1/2)+8

所需的输出 12.5 ,但我的代码返回 12.0

我已经使用过此代码,但这不会给出舍入值

    public String evaluatePostfix(String postfix){

        LongStack S = new LongStack();
        float resout;
        //answer for val1 and val2
        Dialog.alert("postfix: "+postfix + "length "+ postfix.length());  

        for(int k = 0; k < postfix.length(); k++)
        {
            char c =postfix.charAt(k);
            if( c >= '0'&& c <= '9')//i < tokens.length && (Character.isDigit(tokens[i]) || tokens[i] == '.')
            S.push((c - '0'));

            else if (c == '+' || c== '-' || c == '*' || c == '/' || c == '%' || c == '~')
            {
                if(S.isEmpty()) throw new RuntimeException("Empty Stack");
                float RightOp = S.pop();
                Dialog.alert(": "+ RightOp);
                if( c == '~') S.push( (long) -RightOp);
                if(S.isEmpty()) throw new RuntimeException("Empty Stack.");
                switch (c)
                {
                case '+' : S.push((long) (S.pop() + RightOp)); break;
                case '-' : S.push((long) (S.pop() - RightOp)); break;
                case '*' : S.push((long) (S.pop() * RightOp)); break;
                case '/' : S.push((long) (S.pop()/ RightOp)); break;
                case '%' : S.push((long) (S.pop() % RightOp)); break;

                }// END of switch
            }

            else if ( c != ' ')throw new RuntimeException("Error!");
        }
        Dialog.alert(Long.toString(S.pop()));

        Float fX = new Float(S.pop());
        Formatter f = new Formatter(); 
        String result = f.formatNumber(fX.floatValue(), 2);
        return result;

    }

1 个答案:

答案 0 :(得分:2)

问题是,由于您将数字存储为long,因此数据类型会丢失小数。用于存储小数的更好的数据类型是双精度,因为它允许小数并且具有应该对计算器来说足够的范围