Domanda

Really new to programming so I hope this question isn't too annoying but I have hit a wall. I have to make a currency converter in c#, where there is 5 currencies with a stated value each. The console should ask thee user how much they want to convert, what they want to convert to and then display something like "you entered 25 EUR which converts to 27 USD

        double amount;
        double USD = 1.39;
        double GBP = .82;
        /*double CHF = 1.22;
        double AUD = 1.48;
        double CAD = 1.51;*/
        string currency;

        Console.WriteLine("Please enter the amount of Euro you wish to be converted:");
        amount = double.Parse(Console.ReadLine());

        Console.WriteLine("");
        Console.WriteLine("Please choose the currency you wish to convert to:");
        Console.WriteLine("USD");
        Console.WriteLine("GBP");
        Console.WriteLine("CHF");
        Console.WriteLine("AUD");
        Console.WriteLine("CAD"); 
        Console.WriteLine("");
        currency = Console.ReadLine();

        switch (currency)
        {
            case "USD":
            Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount,      amount * currency, currency);
                break;
            case "GBP":

            default:
            Console.WriteLine("You did not enter a valid currency");
                break;
            }
            Console.ReadLine();

"Operator * cannot be applied to operators of type double and string" is the error message Im receiving.

How do I resolve this?

È stato utile?

Soluzione 2

Well I was reading this in bed on my windows phone and it was bugging me. So now I am up late at night typing this!

The problem is you are reading in currency as a string which will contain USD, GBP:

currency = Console.ReadLine();

And reading amount in as a string and converting to a double - for example 300.0:

amount = double.Parse(Console.ReadLine());

You are then using both variables in a multiplication to get the converted amount:

Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount,      amount * currency, currency);

With amount * currency.

You have 2 types which cannot be multiplied together. String and Double! Thus you get a design-time error. Which you will see in the Visual Studio errors window:

Error   1   Operator '*' cannot be applied to operands of type 'double' and 'string'

You basically want to take the entered currency which is "USD", "GBP" and get the appropriate conversion factor from the variable you have named USD or GBP.

So in order to make your code "work" you need to do something like as follows:

switch (currency)
{
    case "USD":
        Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount,      amount * USD, currency);  // <-- here is the change
            break;
    ...
}

In the switch... case you know what the currency value is. The above is case "USD" so you need to reference the USD variable.

To make your code better, get rid of that switch. I would prefer a Dictionary where you could essentially store your strings (GBP, USD, etc) and have an associated conversion factor with each. But you would be getting introduced to the world of generics, but just get a grasp of some of the basics would be your best introduction to programming. But here you go!

        double amount;
        /* Dont need to declare these explicitly!            
        double USD = 1.39;
        double GBP = .82;
        double CHF = 1.22;
        double AUD = 1.48;
        double CAD = 1.51;*/
        string currency;
        Dictionary<string, double> factors = new Dictionary<string, double>();
        factors.Add("GBP", 0.82D);
        factors.Add("USD", 1.39D);
        // ... add other factors

        Console.WriteLine("Please enter the amount of Euro you wish to be converted:");
        amount = double.Parse(Console.ReadLine());

        Console.WriteLine("");
        Console.WriteLine("Please choose the currency you wish to convert to:");
        Console.WriteLine("USD");
        Console.WriteLine("GBP");
        Console.WriteLine("CHF");
        Console.WriteLine("AUD");
        Console.WriteLine("CAD");
        Console.WriteLine("");
        currency = Console.ReadLine();

        double factor;
        if (factors.TryGetValue(currency, out factor))
        {
            Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount, amount * factor, currency);
        }
        else
        {
            Console.WriteLine("You did not enter a recognised currency {1}", currency);
        }

Altri suggerimenti

As it is, this code will try to compare the value of currency to the exchange rate. While that is possibly an interesting idea, I don't think it is what you want. For starters, currency is likely supposed to be a string, so I will go with that assumption. Your comparisons should be against strings, not doubles, but what you typed compares currency to the doubles you defined earlier to denote the exchange rate. What you likely want is:

if (currency == "USD")
    Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount, amount * currency, currency);

and so on. However, in this case your code will look much nicer with a switch statement, as such:

switch(currency)
{
    case "USD":
        Console.WriteLine("You have entered {0} EUR which converts to {1} {2}", amount, amount * currency, currency);
        break;
    case "GBP":
    ...
    default:
        Console.WriteLine("You did not enter a valid currency");
        break;
}

EDIT 1:

To explain why this doesn't compile, the problem is that you have the statement

currency == USD

This statement means compare the variable currency to the variable USD. USD is a double and currency is a string. The compiler does not know how to compare a double and a string (at least using a == operator). Putting double quotes around a constant, like "USD", tells the compiler to instead make a temporary string which has the value of that constant. Of course, the == operator works between strings, so while

double USD = 1;
String currency = "1";
bool result = currency == USD;
bool result2 = currency == 1;

Generates two compiler errors,

String USD = "1";
String currency = "1";
bool result = currency == USD;
bool result2 = currency == "1";

Will be true for both statements.

The currency variable should be a string and the comparison should look like if (currency == "USD")

Use following piece of code.

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
    string Output = "";
    const string fromCurrency1 = "USD";
    const string toCurrency1 = "INR";
    const double amount1 = 2000;

    // Construct URL to query the Yahoo! Finance API
    const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
    string url = string.Format(urlPattern, fromCurrency1, toCurrency1);

    // Get response as string
    string response = new WebClient().DownloadString(url);

    // Convert string to number
    double exchangeRate =
        double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);

    // Output the result
    Output=(amount1*exchangeRate).ToString();

    return Output;
// Ref: http://salmankavish.blogspot.in/2016/02/currency-converter-using-c.html
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top