This problem is a typical homework question. The code presented here may contain some elements that may be a little "ahead of the game" in coursework, but it presents some of the basic elements that might be used in such an exercise.
Currency Converter
#include <stdio.h>
#include <string.h>
const char Description[] =
"Currency Conversion As of June 11, 2003 2:35am GMT";
void convert(double amount, const char *from, const char *to)
{
static const struct
{
const char *name;
double rate;
} Xchg[] = /* US Dollar conversion factor */
{
{ "USD", 1.0 },
{ "Lire", 0.000603049 },
{ "Yen", 0.008464602 },
{ "Pound", 1.65123 },
{ "Peso", 0.0940910 },
{ "Canadian", 0.734061 },
};
size_t i,j;
/*
* Search for the name of the currency you want to convert from.
*/
for ( i = 0; i < sizeof Xchg / sizeof *Xchg; ++i )
{
if ( strcmp(Xchg[i].name, from) == 0 )
{
/*
* Found the 'from' currency name; 'i' is the index of it.
* Search for the name of the currency you want to convert to.
*/
for ( j = 0; j < sizeof Xchg / sizeof *Xchg; ++j )
{
if ( strcmp(Xchg[j].name, to) == 0 )
{
/*
* Found the 'to' currency name; 'j' is the index of it.
* Calculate the new value: multiply by the 'from' rate and
* divide by the 'to' rate.
*/
double value = amount * Xchg[i].rate / Xchg[j].rate;
printf("%g %s = %g %s\n", amount, from, value, to);
return;
}
}
printf("Cannot convert to \"%s\"\a\n", to); /* 'to' name not found */
return;
}
}
printf("Cannot convert from \"%s\"\a\n", from); /* 'from' name not found */
}
int main(void)
{
puts(Description);
convert( 20.0, "USD", "Pound");
convert(100.0, "Yen", "Lire" );
convert( 20.0, "Euro", "Krone");
convert( 20.0, "USD", "Krone");
return 0;
}
/* my output
Currency Conversion As of June 11, 2003 2:35am GMT
20 USD = 12.1122 Pound
100 Yen = 1403.63 Lire
Cannot convert from "Euro"
Cannot convert to "Krone"
*/
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.