1
私は二重のかいないとして、入力した金額を取ることになっている私のC#クラスのためのプログラムに取り組んでいる、となどドル、四半期、の変化を見つけることが、私が使用している変更変換プログラムのロジック| indexOutOfRange
欲張りアルゴリズム、そして私は、 "2D.exeで 'System.IndexOutOfRangeException'型の未処理の例外が発生しました。
私はまだC#で新しく、JavaとC++のバックグラウンドから来ています。
これまでのところ、私は私のお金のクラスを持っている:
using System;
using static System.Console;
namespace _2D
{
class Money
{
private double dollars, cents;
public void IncrementMoney() { }
public void DecrementMoney() { }
public Money(double dollarsncents)
{
double amountLeftOfDecimal = Math.Truncate(dollarsncents);
double amountRightOfDecimal = Math.Floor(dollarsncents);
this.dollars = Math.Round(amountLeftOfDecimal);
//the following LOGIC needs to be wokred out:
this.cents = Math.Round((amountRightOfDecimal * 100)/100, 2);
}
public Money(int ddollars, int ccents)
{
this.dollars = ddollars;
this.cents = ccents;
}
public override string ToString()
{
return String.Format(dollars + " dollars and " + cents + " cents.");
}
public void CoinAmounts(int inAmount, int remainder, int[] coins)
{
if((inAmount % 0.25) < inAmount)
{
coins[3] = (int)(inAmount/0.25);
remainder = inAmount % (1/4);
inAmount = remainder;
}
if ((inAmount % 0.1) < inAmount)
{
coins[2] = (int)(inAmount/0.1);
remainder = inAmount % (1/10);
inAmount = remainder;
}
if ((inAmount % 0.05) < inAmount)
{
coins[1] = (int)(inAmount/0.05);
remainder = inAmount % (1/20);
inAmount = remainder;
}
if ((inAmount % 0.01) < inAmount)
{
coins[0] = (int)(inAmount/0.01);
remainder = inAmount % (1/100);
}
}
public void PrintChange(int[] arr)
{
if (arr[3] > 0)
Console.WriteLine("Number of quarters: " + arr[3]);
if (arr[2] > 0)
Console.WriteLine("Number of dimes: " + arr[2]);
if (arr[1] > 0)
Console.WriteLine("Number of nickels: " + arr[1]);
if (arr[0] > 0)
Console.WriteLine("Number of pennies: " + arr[0]);
}
}
そして、私のメイン:
using System;
namespace _2D
{
class Program
{
static void Main(string[] args)
{
Money MyMoney = new Money(23, 24);
Console.WriteLine(MyMoney.ToString());
Money dollarCentAmount = new Money(12.45);
Console.WriteLine(dollarCentAmount.ToString());
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Enter an amount you'd like change for: ");
double inAmountDouble = Convert.ToDouble(Console.ReadLine());
int inAmount = Convert.ToInt32(inAmountDouble);
int tochange = inAmount;
int remainder = 0;
int[] coins = new int[3];
MyMoney.CoinAmounts(inAmount, remainder, coins);
Console.WriteLine(" Change for " + inAmount + " is: ");
if (inAmount > 1.0)
{
Console.WriteLine("Number of dollars: " + Convert.ToInt32(inAmount));
}
MyMoney.PrintChange(coins);
Console.ReadKey();
}
}
}
'intに行く配列するコインを宣言[3] =(int)(inAmount/0.25);は配列インデックスが始まるので範囲外です。 0 –
'coins'はあなたの' Main'プログラムではなく 'Money'クラスの一部でなければなりません。 – NetMage
あなたは@johnnyMoppを詳しく説明できますか? –