Solved

# Metric conversion program

Posted on 2003-10-31
2,075 Views
Write a script that will assist the user with metric conversions. Your program should allow the user to specify the names of the units as strings (i.e., centimeters, liters, grams etc. for the metric system and inches, quarts, pounds etc. for the English system) and should respond to simple questions such as
"How many inches are in 2 meters?""How many liters are in 10 quarts?"
Your program should recognize invalid conversions. For example, the question
"How many feet in 5 kilograms?"
is not a meaningful question because "feet" is a unit of length while "kilograms" is a unit of mass.

#include <stdio.h>
#include <string.h>

int main()
{
.......
}
How should I build this problme's code?

maybe, I think I should input the metric like
1 inch = 2.54 cm = 0.0254 m, 1 ft = 30.48 cm = 0.3048 m, 1 yard = 91.44 cm = 0.9144 m
1 mile = 1.609 km = 1609 m
1 Liquid quater = 0.94640 Liters, 1 Dry quater = 1.101 Liters, 1 Gallon = 3.785 Liters
1 Bushel = 35.24 Liters
1 Grain = 0.00006 kilograms, 1 troy ounce = 0.03110 kilograms, 1 troy pound = 0.37320kilograms

Anyway, in this program, the user type in "how many inches are in 2 meters?" and then programming will answer "78.74 inches," right?

How can I do that?
0
Question by:john2789
• 21
• 19
• 2
• +2

Author Comment

ID: 9661687
Should I input these units and make the code in using string?
Physical Quantity    Metric                       English

Length               cm, m, km                     in, ft, yds, miles
Area                 sq_cm, sq_m, sq_km, hectare   sq_in, sq_ft, acre, sq_mi
Volume               ml, cc, l, cubic_m            fl_oz, cu_in, cu_ft, gal
Weight               g, kg, English_tons           oz, lb, metric_tons
Temperature          degrees_C, degrees_K          degrees_F

0

Author Comment

ID: 9661708

Thanks
0

LVL 3

Expert Comment

ID: 9661846
I take it this is homework?

You've got the right idea but you will have a problem when the user inputs "centimeters" instead of "cm".  You've already figured that each class of unit needs to be converted to a common base (1 inch for example)
There used to be a fun little unix program that would do this...

It had a configuration file that looked something like

length  1      meter meters m
length  100 centimeter centimeters cm

etc.

with such a configuration file, you could take your standard input of the form "How many %s are in %f  %s"
look both of your units up and away you go.  Since it was trivial to add new units it was just the thing when you wanted to convert rods to fathoms (yes, it could do that).
0

LVL 15

Expert Comment

ID: 9661862
Don't know whether you'd need this or not but heres a snippet to convert to lower case. If the user typed feet, FEET, FeEt, etc. the program would read it all the same:

#include <ctype.h>

int i;
char input[] = "FeEt";

for(i = 0; i < input[i]; i++)
input[i]=tolower(input[i]);

This will make the input "feet". From there on you could type all your if statements as lowercase.
0

Author Comment

ID: 9661870
This is not an assignment. I don't go to school right now. I have been studying C programming, that's all.

so,

int main()
{
printf("\n How many %s are in %f %s", ...);?
..
....

hmm.... ???? Could you please how I can start with? How can I write the code?
like the following?
string = centimeter, meter, kilogram, gram, miles, feet..?
0

LVL 3

Expert Comment

ID: 9661891
Alright then...

What is the first thing your program needs to do?
What does printf() do?
0

LVL 3

Expert Comment

ID: 9661902
Lets approach this another way.  It might seem tedious but I promise that every line you write now will end up in the finished product.

The program you are trying to write is far too difficult for your first program.  Even very experienced programmers, when faced with a new language start by writing a program that prints the message "Hello World."

Write that program now.  Compile it and run it.

0

LVL 3

Expert Comment

ID: 9661939
Just so that you don't get offended, I have looked over your previous posts and I can see that you are, in fact, trying to teach yourself C.  I can tell this because no teacher would give you the exercises you have picked in the order you have picked them.  If you bear with me and we work through this exercise I can teach you enough C to write a fairly decent program.  Are you cool with that?
E.
0

Author Comment

ID: 9661989
Yeah!! coool!! Please teach me!!
0

LVL 3

Expert Comment

ID: 9661992
Alright!  I like teaching.

So you've got a working hello world, right?  Show me the the code.
0

Author Comment

ID: 9661993
#include <stdio.h>

int main()
{
printf("\n %s", "Hello World" );
return 0;
}

like this, right?
0

Author Comment

ID: 9661998
Or, just should I type like this?

int main()
{
printf("\n Hello World" );
return 0;
}
0

LVL 3

Expert Comment

ID: 9662001
Did this compile and run?  I didn't think so.
0

LVL 3

Expert Comment

ID: 9662003
Oh better.
0

Author Comment

ID: 9662005
It run on the second one
0

LVL 3

Expert Comment

ID: 9662008
Please actually compile and run the code at each stage.  This shows YOU what your changes are doing and, when you run into compiler errors I will be here to work you through them.
0

LVL 3

Expert Comment

ID: 9662016
Great.  Now we are going to add a variable.  Declare "name" to be an array of 20 characters.  Just give it a shot...I'll be here.

0

LVL 3

Expert Comment

ID: 9662041
Here are some variable declarations:

int i;           /* declares i to be an integer */
float f;        /* declares f to be a floating point (real) number */
int ar[10];   /* declares ar to be an array of 10 integers */
char input;  /* declares input to be a character */

0

LVL 40

Expert Comment

ID: 9662133
john:

going back to your original question: you were definately on the right track.

I would do the following:

Keep 1 conversion for each unit.  IE:

3.6 m in a yard.  (not an actual figure)

Then, when you get the units, convert each side to that part:

IE:

100 cm = 1 m, ergo:

how many cm in 1 ft (say the answer is 345)

convert one ft to yards:  .33

.33 * 3.6 (or the real number = number of m in yards)

convert m to cm

Basically, get it down to your base unit, find the ratio, convert it back to what it needs to be.  It's not that hard.  and either hello program would work.
0

LVL 3

Expert Comment

ID: 9662302
ged...
>>>It's not that hard.
Not for you or me.  Read the question history before you post.

>>>and either hello program would work.
Try it.  The first one will compile but give an unexpected result.
0

Expert Comment

ID: 9662354
Hey guynumber5674,

Can you please tell me what is the unexpected result of the hello world program ? i tried it and it worked fine....or was it some beginner's luck ?
0

Expert Comment

ID: 9662358
er, sorry for getting the numbers wrong at the earlier post, guynumber5764.
0

LVL 3

Expert Comment

ID: 9662430
karram... printf("\n %s", "Hello World" ) will compile fine but when it is evaluated there is no string corresponding to %s.  Normally that will either print garbage or abend.
0

LVL 3

Expert Comment

ID: 9663200
john...
the next thing is to get a feel for printing variables using printf() and learning how to read from the standard input using scanf().

I'd like you to put the following code in your hello world program.  I haven't tested it (sorry...I'm not at my usual pc) but it looks right.

int your_number;
printf("\nEnter a number\n");
scanf("%d", &your_number);
printf("\nYour number is %d\n", your_number);

It should be pretty obvious what it is supposd to do.  Note the & in the scanf() is required.Wtihout going into details, all scanned parameters need that EXCEPT strings (%s) which look like this:

scanf("%s", your_name);

I'd like you to play with that a bit.  Make collect a name.  Make it collect 2 numbers and print them on a line:
ie: "what is your first number"
2
"what is your second number"
2
"2 + 2 = 4"
etc.

Please post when you are ready to move on or have a question.
0

Author Comment

ID: 9664954
#include <stdio.h>

int main()
{
int a, b;
printf("\n What is your first number:");
scanf("%d", a);
printf("\n What is your second number:");
scanf("%d", b);
printf("\n %d + %d is %d", a, b, a+b);
return 0;
}

like this?
0

Author Comment

ID: 9665120
#include <stdio.h>
#include <math.h>

int main()
{
int a, b;
printf("\n What is your first number:");
scanf("%d", &a);
printf("\n What is your second number:");
scanf("%d", &b);
printf("\n %d + %d is %d", a, b, a+b);
return 0;
}

like this?
0

Author Comment

ID: 9665389
#include <stdio.h>
#include <math.h>

int main ()
{
string = centimeter, inch;
int a, b;
printf("\n How many %d %s are in %d %s?", a, string, b, string);
1 centimeter = 0.3937 inch;
1 inch = 2.54 centimeter;
if(%s == centimeter, %s == inch)
printf("\n The answer is %f %s", (float)(a/2.54),"inch");
else
printf("\n The answer is %f %s", (float)(2.548xb), "centimeter");
return 0;
}

I tried to do this way. You think this code will work? I am not sure it will work. I think something is not right. Or, I am thinking I should use "switch structure" then let the user select length or volume or...
0

LVL 3

Expert Comment

ID: 9666601
9:51 post.   Excellent.  It looks like you tried it and fixed your mistake.   I'd like you to now modify it to read (using scanf) a name and to print that name.  Re-read (11/01  9:05AM) post if the scanf() gives you grief.  Note that C does not have a "string" data type per se.  What we call a "C String" is an array of char where the last character of the string is an ascii NUL ('\0' ascii value 0..not the same as the digit '0' whose ascii value is 32).
So in C, "Hello world" is shorthand for an array of characters {'H', 'e', 'l','l','o',' '.'w','o','r','l','d',''\0'}.  That's not terribly important right now but should always be the the back of your mind.

char teststring[20] = "Hello world";
and
char teststring[20] = {'H', 'e', 'l','l','o',' '.'w','o','r','l','d',''\0'};
are absolutely equivalent.

That'll get you through the next step.
Last Post...
It is OK to try stuff (of course!!!) but you've got to compile and test your work.  What you submitted might compile in a very old compiler but that first line ("string = ...") will definitely cause a newer compile will at least generate a warning to the effect of :
"Warning:  undeclared identifier: string.   int assumed."
followed by many more warning and errors.

The reason is that there is no native data type "string" in C (see above).  So the compiler thinks that "string" is a variable that you forgot to declare.  Old, old (what we call K&R) C would simply assume that the variable was an integer.

Feel free to post compiler warnings and errors.  The whole exercise ultimately about being able to talk to a compiler.

0

Author Comment

ID: 9668153
how about, if I write like #include <string.h>, does this work?
0

Author Comment

ID: 9698465
#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{

float a, b;

char units [ 7 ] = {inches, meters, quarts, liters, pounds, kilograms, feet};
unit [0] = inches;
unit [1] = meters;
unit [2] = quarts;
unit [3] = liters;
unit [4] = pounds;
unit [5] = kilograms;
unit [6] = feet;

printf("\n Enter a number");
scanf("%.2f", &a)
printf("\n Select the units you want to convert");
for(i=0; i<7; i++)
{
printf("\n How many %s  are in %.4f %s ?" , unit[i], a, unit[i]);
scanf("%s %.4f %s", "unit[MAX]", &a, "unit[MAX]");
printf("\n %.4f %s",
if(

0

LVL 3

Expert Comment

ID: 9698605
What is the compiler error?
Probably something to the effect of "inches: undeclared identifier" right?

In C you've got your basic variable types and the associated constants.
ie:

int i;   and       i = 6;
float f;   and    f = 6.2;
char c;   and    c = 'd'

compare the last line to:
c = d

Notice that in the latter case, the compiler might not be able to tell if  "d" is a constant (ie: an actual 'd') or a variable.  The way C distinguishes is by the use of single quotes (for single characters) or double quotes (for strings).  This is pretty much the same for ALL programming languages!

so when the compiler conplained about an undeclared identifier it was telling you that it thought "inches" was a variable but it couldn't see where you had declared it.
char units [ 7 ] = {"inches"  etc.

I suggest you reread my last post and try that exercise again. It addresses this exact issue.

You should also invest in 2 good C books:
1) a structured learning book such as "Learn C in 21 Days"
2) a language reference such as "A Book on C" (author?)  or  "The C Programming Language" (Kernigan & Ritchie)
The first one will help you learn the language.  The 2nd will live on your desk forever.
I have been programming C & Unix for 17 years and have well-used copies of "OOP with C++ in 21 days" (Perry) and "Programming In C" (Kochan) in arms reach.
0

LVL 3

Expert Comment

ID: 9698619
Oh yeah...
Your #includes are fine.  You probably won't need <math.h> though.   It is mostly for square roots and trig and stuff.  Basic math is built right into the language.
0

Author Comment

ID: 9700086
char units [ 45 ] = {"inches", "meters", "quarts", "liters", "pounds", "kilograms", "feet"};
...
...
...
printf("\n How many %s  are in %.4f %s ?" , unit[i], a, unit[i]);
scanf("%s %.4f %s", "unit[i]", &a, "unit[i]");
if((i==inches) && (i==meters)&&(i==feet))
{
printf("\n %.4f %s", &a, "unit[i]");
inches* = 0.0254*a meters;
meters/ =  a / 39.3701 inches;
feet* = 0.3048*a meters;
meters / = a / 3.28084 feet;
inches* = a*.083333 feet;
feet * = a* 12 inches;
meters * = a * 1 meters;
inches * = a * 1 inches;
feet * = a * 1 feet;
return;
}
else((i==inches, meters, feet) != (i==pounds, kilograms, quarts, liters))
printf("\n\n ERROR");

if((i==quarts)&&(i==liters))
{
printf("\n %.4f %s", &a, "unit[i]");
quarts * = a* 0.946 liters;
quarts * = a * 1quarts;
liters *= a * 1.057 quarts;
liters * =  a * 1 liters;
return;
}
else((i==quarts, liters) != (i=inches, meters, feet, kilograms, pounds))
printf("\n\n ERROR);

if((i==pounds)&&(i==kilograms))
{
printf("\n %.3f %s", &a, "unit[i]");
pounds * = a * 0.453592 kilograms;
pounds * = a * 1 pounds;
kilograms * = a * 2.20462 pounds;
kilograms * = a * 1 kilograms;
return;
}
else((i==pounds, kilograms) != (i== inches, meters, feet, quarts, liters))
printf("\n\n ERROR");
return 0;

0

Author Comment

ID: 9700090
return 0;
}
0

LVL 3

Accepted Solution

guynumber5764 earned 500 total points
ID: 9703131
I doubt this compiled.
0

Author Comment

ID: 9703216
yeah, I make sure it won't work. One my computer which has C progamming was broken, so I cannot type my codes. However, I am sure that this won't work. I just tried to do my best and thought harder and harder. I used array and string, I think I cannot make the code for this problem. It is tooooo difficult for me. I think I should give up solving this problem.
0

Author Comment

ID: 9703296
#include <stdio.h>

int main()
{
char str[100];
char *str2 = "I gave up solving this problem";
str2 = str;
strcpy(str, "I gave up this \' ****in\' problem");
printf("\n\n\n Thank you very much");
return 0;
}
0

LVL 3

Expert Comment

ID: 9703499
You are welcome.
Don't be discouraged.  You took on a pretty challenging problem and, in the process, learned a bunch of C.  If you can find an "introduction to C"-type course or a book with a structured approach to teaching C you will find it easier.  The fact is that you are trying to learn a new language.  Without knowing the language, it is very difficult to judge how hard a given problem is.  The books and the courses will give you the excercises in a logical sequence with plenty of explanation and feedback at each step of the way.

0

LVL 3

Expert Comment

ID: 9703557
Also always remember that the compiler is trying to talk to you.  Listen carefully and try to figure out what the warningas and errors mean to get real insights into how the language works.  If you get stuck on an error you can always open a question here with both the error message and the code from a few lines around the error.  The experts are always happy to answer a question in that format.

One more thought.  When the compiler completely barfs and gives you a million error messages just worry about the first one.  Fixing it will often fix everything.  You will soon understand why.
0

Author Comment

ID: 9705361
TELL ME THE ANSWER
0

LVL 3

Expert Comment

ID: 9705426
NO.

But seriously.  As you have already seen, canned answers do nothing towards learning to program.  You've "worked" your way through several hundred lines of code by being given the answer and you are still writing stuff like :

else((i==quarts, liters) != (i=inches, meters, feet, kilograms, pounds))

Does that line actually make any sense to you?  I'm not talking C or VB or Pascal here...just does it make any sense at all!?
I have a feeling that you are just throwing stuff at the wall and seeing what sticks.

I am happy to help you learn but you've gotta meet me 1/2way.
E.
0

Author Comment

ID: 9705449
So what? I just did my best and thought harder without going to work. I spent a lot of times on this and I didn't know that this code: else((i==quarts, liters) != (i=inches, meters, feet, kilograms, pounds)) works or not.

I just gave up this stuff, but not throwing away whole C programming. I'll do my best way to think and study C once again from beginning. SO, DON'T **** ME UP and FEEL THAT I AM JUST THROWING AWAY STUFF AT THE WALL AND SEEING WHAT STICKS!!!
0

Author Comment

ID: 9706697
OK, HOW ABOUT THIS? I have tried to made this code. I typed this code on dad's C programming software, and I had so many errors.

#include <stdio.h>
#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int IsValidQuestion(char *,char *);
int FindIndex(char **,char *,int);

char *Length[]={"inches","feet","meters"};
float M_Length[]={.0833,1.0,.3048};

char *Weight[]={"pounds","kilograms"};
float M_Weight[]={.453,1.0};

char *Volume[]={"quarts","liters"};
float M_Volume[]={0.9464,1.0};

int main()
{
char choice, *Question;
printf("Ask the Question :");
fflush(stdin);
gets(Question);
getch();
exit(0);
return 0;
}

{
char *Mes_A;
char *RMes_B;
char *Number;

for(int loop=9,i=0;Question[loop]!=' ';loop++,i++)
Mes_A[i]=Question[loop];
Mes_A[i]='\0';

for(loop=strlen(Question)-2,i=0;Question[loop]!=' ';loop--,i++)
RMes_B[i]=Question[loop];
RMes_B[i]='\0';

for (loop=0;loop<strlen(Question);loop++)
{
if(isdigit(Question[loop])!=0)
{
for(int k=loop,j=0;Question[k]!=' ';k++,j++)
Number[j]=Question[k];
Number[j]='\0';
break;
}
}
if(IsValidQuestion(Mes_A,strrev(RMes_B)))
{
char Type;
int l1=0,l2=0;
float N=atof(Number);
printf("%f\n",N);
puts("Valid Question");
printf("What variable the strings are describing:\n");
printf("Length[L]/Weight[M]/Volume[V] :");
fflush(stdin);
scanf("%c",&Type);
if(toupper(Type)=='L')
{
l1=FindIndex(Length,Mes_A,3);
l2=FindIndex(Length,strrev(RMes_B),3);
if(l2-1>l1)
printf("%f %s",N*M_Length[l2-1]/M_Length[l1],Mes_A);
else
printf("%f %s",N*M_Length[l1]/M_Length[l2-1],Mes_A);
getch();
}
if(toupper(Type)=='M')
{
l1=FindIndex(Weight,Mes_A,2);
l2=FindIndex(Weight,strrev(RMes_B),2);
if(l2-1>l1)
printf("%f %s",N*M_Weight[l2-1]/M_Weight[l1],Mes_A);
else
printf("%f %s",N*M_Weight[l1]/M_Weight[l2-1],Mes_A);
getch();
}
if(toupper(Type)=='V')
{
l1=FindIndex(Volume,Mes_A,2);
l2=FindIndex(Volume,strrev(RMes_B),2);
if(l2-1>l1)
printf("%f %s",N*M_Volume[l2-1]/M_Volume[l1],Mes_A);
else
printf("%f %s",N*M_Volume[l1]/M_Volume[l2-1],Mes_A);
getch();
}
}
else
puts("Invalid Question");
getch();
}

int IsValidQuestion(char *A,char *B)
{
int flag1l=0,flag2l=0;
int flag1w=0,flag2w=0;
int flag1v=0,flag2v=0;

for(int loop=0;loop<3;loop++)
{
if(strncmpi(A,Length[loop],strlen(A))==0)
flag1l=1;
if(strncmpi(B,Length[loop],strlen(B))==0)
flag2l=1;
}

for(loop=0;loop<2;loop++)
{
if(strncmpi(A,Weight[loop],strlen(A))==0)
flag1w=1;
if(strncmpi(B,Weight[loop],strlen(B))==0)
flag2w=1;
}
for(loop=0;loop<2;loop++)
{
if(strncmpi(A,Volume[loop],strlen(A))==0)
flag1v=1;
if(strncmpi(B,Volume[loop],strlen(B))==0)
flag2v=1;
}
if(flag1l==1&&flag2l==1||flag1w==1&&flag2w==1
||flag1v==1&&flag2v==1)
return 1;
else
return 0;

}

int FindIndex(char *Array[],char *key,int N)
{
for(int loop=0;loop<N;loop++)
{
if(strcmpi(Array[loop],key)==0)
break;
}
return loop;
}
0

LVL 3

Expert Comment

ID: 9709403
That looks much better.

Wtihout seeing your compiler errors I can only guess where your prolems are.  Here's two big hints though...

1) Use  "char Question[80];"  instead of "char *Question;"  to declare string variables (not in the function header though).  Since arrays have their own storage (pointers do't), they are much easier to use.

2) Rather than trying to figure out all the ins and outs of a sophisticated input parser, start out by just using scanf() to accept input of the simplest possible form: "%s %f %s".

E.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ouâ€¦
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and infâ€¦
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.

#### 828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.