题目描述:
我们知道计算机的大小单位有 B, KB, MB 等,现在请你编写一个计算器进行大小单位换算。
输入格式:输入一个字符串,由一个 0 到 1023 之间的整数,一个单位名称(大写字母),一个等于号和问号,以及第二个单位名称。
单位只有可能是 GB,MB,KB,B 之间的一个。
输出格式:输出一个数字,精确到小数点后 6 位。
输入输出样例:
输入 #1
128MB=?GB
输出 #1
0.125000
输入 #2
64MB=?KB
输出 #2
65536.000000
Java代码:
import java.util.Scanner;
public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);String s = scanner.next();int[] curNum = new int[4];int count = 0, Num = 0;double toNum = 0;char curChar = 0, toChar = 0;for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '?'){toChar = s.charAt(i + 1);break;}}for (int i = 0; i < s.length(); i++) {if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z'){curChar = s.charAt(i);break;}curNum[i] = s.charAt(i) - '0';count++;}for (int i = 0; ; i++) {Num += curNum[i] * Math.pow(10,count-1);count--;if (count == 0) break;}if (curChar == 'G'){if (toChar == 'M'){toNum = Num * Math.pow(2,10);}else if (toChar == 'K'){toNum = Num * Math.pow(2,20);}else if (toChar == 'B'){toNum = Num * Math.pow(2,30);}else toNum = Num;}if (curChar == 'M'){if (toChar == 'G'){toNum = Num * Math.pow(2,-10);}else if (toChar == 'K'){toNum = Num * Math.pow(2,10);}else if (toChar == 'B'){toNum = Num * Math.pow(2,20);}else toNum = Num;}if (curChar == 'K'){if (toChar == 'G'){toNum = Num * Math.pow(2,-20);}else if (toChar == 'M'){toNum = Num * Math.pow(2,-10);}else if (toChar == 'B'){toNum = Num * Math.pow(2,10);}else toNum = Num;}if (curChar == 'B'){if (toChar == 'G'){toNum = Num * Math.pow(2,-30);}else if (toChar == 'M'){toNum = Num * Math.pow(2,-20);}else if (toChar == 'K'){toNum = Num * Math.pow(2,-10);}else toNum = Num;}System.out.printf("%.6f",toNum);}
}