1906 - 小小计算器

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

编写一个小小的计算器,能够计算两个浮点数的加、减、乘、除。

题目输入

每行是一个测试用例,每行的内容为:操作数1 运算符 操作数2,操作数为浮点数,运算符为+、-、*、/,操作数和运算符之间有一个空格隔开。

题目输出

对每个测试用例,输出一行计算结果,保留两位小数的精度。如果除法遇到操作数2为0,输出“Divide by zero."。

输入/输出样例

输入格式

1.2 + 3.51
-3 * -2.4
6.4 / 2
5 / 0

输出格式

4.71
7.20
3.20
Divide by zero.

C语言解答

#include <stdio.h>
#include <math.h>

int main()
{
    double a, b, s;
    char c;
    int Flag;
    while(scanf("%lf %c %lf", &a, &c, &b)!=EOF)
    {
        Flag = 0;
        switch(c)
        {
            case '+':
            {
                s = a + b;
                break;
            }
            case '-':
            {
                s = a - b;
                break;
            }
            case '*':
            {
                s = a * b;
                break;
            }
            case '/':
            {
                if(fabs(b) <= 1e-7)
                {
                    Flag= 1;
                }
                else
                {
                    s = a / b;
                    break;
                }
            }
        }
        if(!Flag)
        {
            printf("%.2f\n", s);
        }
        else
        {
            printf("Divide by zero.\n");
        }
    }
    return 0;
}

C++解答

#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
    float a,b;
    char t;
    cout << setiosflags(ios::fixed)<< setiosflags(ios::left)<<setprecision(2);
    while(cin >> a >> t >> b)
    {
              switch(t)
              {
                       case '+':cout << a+b;break;
                       case '-':cout << a-b;break;
                       case '*':cout << a*b;break;
                       case '/':if(b==0) cout << "Divide by zero."; else cout << a/b;break;
              }
              cout << endl;
    }
    return 0;
}

Java解答

import java.util.Scanner;
//import java.io.*;
public class Main {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		Float a,b;
		char c;
		while(in.hasNext()){
			a=in.nextFloat();
		    c=in.next().charAt(0);
			b=in.nextFloat();
			if(c=='+'){
				System.out.println(new java.text.DecimalFormat("0.00").format(a+b));
			}
			if(c=='-'){
				System.out.println(new java.text.DecimalFormat("0.00").format(a-b));
			}
			if(c=='*')
			{
				//System.out.println(a*b);
				System.out.println(new java.text.DecimalFormat("0.00").format(a*b));
			}
			if(c=='/'){
				if(b==0){
					System.out.println("Divide by zero.");
				}
				else {
					System.out.println(new java.text.DecimalFormat("0.00").format(a/b));
				}
			}
			}
			
		}
		
	}