第三章第三十一题(金融:货币兑换)(Financials: currency exchange)
第三章第三十一题(金融:货币兑换)(Financials: currency exchange)
*3.31(金融:货币兑换)编写一个程序,提示用户输入从美元到人民币的兑换汇率。然后提示用户输入0表示从美元兑换为人民币,输入1表示从人民币兑换为美元。继而提示用户输入美元数量或者人民币数量,分别兑换为另外一种货币。
下面是示例:
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 to convert dollars to RMB and 1 vice versa:0
Enter the dollar amount:100
100.0 is 681.0 yuan
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 to convert dollars to RMB and 1 vice versa:1
Enter the RMB amount:10000
10000.0 yuan is 1468.43
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 to convert dollars to RMB and 1 vice versa:5
Incorrent input
*3.31(Financials: currency exchange) Create a program that asks the user for the exchange rate from U.S. dollars to Chinese RMB. Request the user to input 0 to convert dollars to RMB and 1 to convert RMB to dollars. Ask the user for the amount in either currency and convert it accordingly.
Here are some sample runs:
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 or 1: 5
Invalid input
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 or 1: 0
123.45 equals 779.45 yuan
Enter the exchange rate from dollars to RMB:6.81
Enter 0 or 1:7
Invalid input
参考代码:
package chapter03;
import java.util.Scanner;
public class Code_31 {
public static void main(String[] args) {
double exchangeRate,moneyAmount,exchangedAmount;
final int exchangeMode;
System.out.print("Enter the exchange rate from dollars to RMB: ");
Scanner input = new Scanner(System.in);
exchangeRate = input.nextDouble();
System.out.print("Enter 0 to convert dollars to RMB and 1 vice versa: ");
exchangeMode = input.nextInt();
if(exchangeMode == 0)
{
System.out.print("Enter the dollar amount: ");
moneyAmount = input.nextDouble();
exchangedAmount = moneyAmount * exchangeRate;
System.out.println("$" + moneyAmount + " is " + exchangedAmount + " yuan");
}
else if(exchangeMode == 1)
{
System.out.print("Enter the RMB amount: ");
moneyAmount = input.nextDouble();
exchangedAmount = moneyAmount / exchangeRate;
System.out.println(moneyAmount + " yuan is $" + exchangedAmount);
}
else
System.out.println("Incorrect input");
input.close();
}
}
java

- 结果显示:
Enter the exchange rate from dollars to RMB: 6.81
Enter 0 to convert dollars to RMB and 1 vice versa: 0
Enter the dollar amount: 100
$100.0 is 681.0 yuan
Process finished with exit code 0
java
