我有一个问题,我必须做一个学校的作业。我在处理小数时遇到了麻烦。如果有人能帮我让程序接受小数。它会输出一个小数,但不允许我输入一个。
using System;
public class Bank_Account
{
public static void Main()
{
char input, C, D, P, Q;
double balance;
Console.WriteLine("Please enter C for Cheque, D for Deposit, P for Print or Q to quit");
input = Convert.ToChar(Console.ReadLine());
do
{
switch (input)
{
case 'D':
Deposit(ref balance);
break;
case 'P':
Print(balance);
break;
case 'C':
Cheque(ref balance);
break;
default:
Console.WriteLine("{0} is not a valid choice", input);
break;
}
} while (input != 'Q');
}
public static void Deposit(ref double balance)
{
double deposit;
Console.WriteLine("Enter the amount you want to deposit: ");
deposit = Convert.ToInt32(Console.ReadLine());
if (deposit > 1000)
{
deposit = deposit*1.02;
}
else
{
deposit = deposit;
}
balance = +deposit;
}
public static void Cheque(ref double balance)
{
var tempBalance = balance;
double deduction;
const double fee = 1;
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToInt32(Console.ReadLine());
} while (deduction < 0);
tempBalance = balance - deduction - fee;
if (tempBalance < 0)
{
Console.Write("Not enough money in the account");
}
else
{
balance = tempBalance;
}
}
public static void Print(double balance)
{
Console.WriteLine("Your current balance is {0.00}", balance);
}
}
修改如下:
deposit = Convert.ToInt32(Console.ReadLine());
:
deposit = Convert.ToDouble(Console.ReadLine());
,因为你读的不是整型,而是双精度。像另一个答案中建议的那样使用TryParse
会更好。此外,如果你需要精度,也许你应该使用十进制而不是双精度,但如果精度不那么重要,则使用双精度。
要转换为整型,像这样修改
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToDouble(Console.ReadLine());
}
Try This:
double deposit;
double.TryParse(Console.ReadLine(),out deposit);
deposit = Double.Parse(Console.ReadLine());