gpt4 book ai didi

c# - 无法从 double 转换为十进制错误

转载 作者:太空狗 更新时间:2023-10-29 22:10:37 25 4
gpt4 key购买 nike

对于此作业,我需要使用 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

我不知道是什么导致了这些错误,因为我认为我没有使用过 double 一次,而且非常快速地谷歌错误并没有帮助我。

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 literal相反:

 BankAccount account = new BankAccount(142.50m);

注意数字后面的m

关于c# - 无法从 double 转换为十进制错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26737507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com