Money Maker projects bug

Hello,

I was doing the money maker project for c# to use Math class and methods.
When arriving to the end and trying to print out and then doing the dotnet run to check if everything was okay, I had an error coming from the command line.

Program.cs(15,31): error CS0121: The call is ambiguous between the following methods or 
properties: 'Math.Floor(decimal)' and 'Math.Floor(double)' 
[/home/ccuser/workspace/csharp-money-maker/MoneyMaker.csproj]

Just to be sure I checked both Math.Floor I used to get the amount of coins corresponding and it seems fine.
So I just searched on and on it seems that the problem come from goldValue and silverValue type making it ambiguous for .NET? Making them as double seems to fix it.

But the hint tells us to make these as int. And as well as many people did, I guess we naturally did ints.

Just to be sure, here’s my original code making it bug.

using System;

namespace MoneyMaker
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Welcome to Money Maker!");
      Console.WriteLine("Enter a number: ");
      int amount = Convert.ToInt32(Console.ReadLine());
      Console.WriteLine($"{amount} cents is equal to...");

      //coins values
      int goldValue = 10;
      int silverValue = 5;

      //calculating
      double goldCoins = Math.Floor(amount / goldValue);
      double remainder = amount%goldValue;
      double silverCoins = Math.Floor(remainder / silverValue);
      remainder %= silverValue;

      //output results
      Console.WriteLine("Gold coins: " + goldCoins);
      Console.WriteLine("Silver coins: " + silverCoins);
      Console.WriteLine("Bronze coins: " + remainder);
      
    }
  }
}

Hi,
Where you vary to the course is it asks for the input to be converted to a double not an int;
i.e,

double amount  = Convert.ToDouble(Console.ReadLine());

What’s causing the error is a couple of things.
Firstly, c# does something called integer division. When you divide one int with another, you’ll get the floor of the result automatically.
e.g.
10/7 would equal 1
So, you’re effectively calling Math.Floor on an integer.

Secondly, Math.Floor has two implementations. One returns a double, the other a decimal. It chooses which to use based on the value in the brackets.
As that’s an integer it could equally be either, so it gives you the error rather than guessing - which, as double and decimal have differing levels of precision, could cause bigger problems.

Basically, it’s saying I’m not quite sure what you want me to do with this so I’m not going to do anything until you’re a bit clearer. Some other programming languages might not be as strict, but c# is fairly type safe - i.e. every object/variable is assigned to be a certain type (int, string, double, etc) and that determines how it can be used.

Hope that helps

1 Like