无法从双精度转换为十进制错误
本文关键字:十进制 错误 转换 双精度 | 更新日期: 2023-09-27 18:29:15
对于这个任务,我需要用BankAccount程序做一些事情,但首先我需要复制并运行示例。我已经从作业表中复制了代码,如下面的屏幕截图所示,但我得到了下面所示的错误。
Error 2 Argument 1: cannot convert from 'double' to 'decimal' Line 13 Column 51
Error 1 The best overloaded method match for 'BankAccount.BankAccount.BankAccount(decimal)' has some invalid arguments Line 13 Column 35
Error 4 Argument 1: cannot convert from 'double' to 'decimal' Line 13 Column 30
Error 3 The best overloaded method match for 'BankAccount.BankAccount.Withdraw(decimal)' has some invalid arguments Line 18 Column 13
我不知道是什么导致了这些错误,因为我认为我没有使用过替身,而且谷歌快速搜索错误对我没有帮助
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankAccount
{
class Program
{
static void Main(string[] args)
{
// Create Bank Account & Print Balance
BankAccount account = new BankAccount(142.50);
Console.WriteLine("Account Balance is: " + account.ToString());
// Withdraw £30.25
Console.WriteLine("Withdrawing £30.25");
account.Withdraw(30.25);
// Print balance again
Console.WriteLine("Account Balance is: " + account.ToString());
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankAccount
{
public class BankAccount
{
private decimal _balance;
public decimal Balance
{
get { return _balance; }
private set { _balance = value; }
}
//Constructor: Constructs a new Bank Account with 0 balance
public BankAccount()
{
Balance = 0;
}
//Constructor: Constructs a new Bank Account with the specified balance
public BankAccount(decimal balance)
{
Balance = balance;
}
//Deposits the specified amount into the Bank Account
public void Deposit(decimal amount)
{
Balance += amount;
}
//Withdraws the specified amount from the Bank Account
public void Withdraw(decimal amount)
{
Balance -= amount;
}
//ToString Override
public override string ToString()
{
return string.Format("{0}: Balance = {1}", "BankAccount", Balance);
}
}
}
此处:
BankAccount account = new BankAccount(142.50);
您正在传递double
文字142.50
。然而,BankAccount需要decimal
文字:
BankAccount account = new BankAccount(142.50m);
注意数字后面的m
。
MSDN中有一个关于C#的decimal
的简单答案(甚至是示例)。
你有权使用decimal
进行这种操作:
decimal关键字表示128位的数据类型。与浮点类型相比,十进制类型具有更高的精度和更小的范围,这使其适用于财务和货币计算。
使用decimal
文字需要m
后缀:
如果您希望将数字实数视为十进制,请使用后缀m或m,例如:
decimal myMoney = 300.5m;
如果没有后缀m,该数字将被视为双精度,并生成编译器错误
另外还有两个来自文档的导入点:
浮点类型和十进制类型之间没有隐式转换;因此,必须使用强制转换在这两种类型之间进行转换。
您也可以在同一表达式中混合使用十进制和数字积分类型。但是,在没有强制转换的情况下混合使用十进制和浮点类型会导致编译错误。
这一点很重要,这样你就不会慢慢地建立误差,例如,通过对许多0.1
求和,这是二进制的周期数。