Simple Conversion tool

This is a discussion on Simple Conversion tool within the C Programming forums, part of the General Programming Boards category; hey all, new here and new to coding in general. I've got two problems First, I'm working on a project ...

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    8

    Simple Conversion tool

    hey all,

    new here and new to coding in general.

    I've got two problems

    First, I'm working on a project that requires us to make a program that can converts several different distance types, the program needs to:

    -Have the user input a distance with units (either m(meters),M(miles),km(kilometers),ft(feet))

    -the program needs to read the number and the units and perform the appropriate conversion(meters-->kilometers,ft-->miles, and vice versa)

    -the program then needs to display the result with the new units (of course!)

    for example: input= 1000 m output= 1 km

    I think I'm grasping this pretty well, but im having trouble getting scanf to read both the number and units correctly. I believe I may need to utilize pointers, but my knowledge here is pretty damn shalllow. I've tried all sorts of combinations of code, i either get a compiler error, something like: incompatible types in assignment, function not defined, assignment of read only location. These vary depending on the nuances i change. If it does manage to compile, then usually I get a segmentation fault once i enter in a value.

    so anyway, I'm just trying to get one block of code to work. I should be able to go in later and put in all the if and else statements needed to specify the different conversions.
    the code

    Code:
    #include <stdio.h>
    
    
    
    
    
    main() {
    
    
    
      /* declare main program variables */
    
    int number;
    char unit[2];
    int ConvNum;
    
    printf("Please enter the value that you wish to convert (including units):");
    scanf("%d %s", &number,unit);
    
     if(unit="%s","m"){
    ConvNum=number*.001;
    printf("%d meters is equal to %d Miles",number,ConvNum);
    return 0;
    }
    }
    also, our other project requires us to make a program that
    A.)Reads data from an array
    A.)reorders the array in either ascending or descending order (users choice) and writes the new array to a new file, specified by the user
    B.)Prints first, last, and median number after reorder

    the problem I'm having with this one is that the program seems to be adding a random, very large, number in the final array (the reordered one). This of course changes the total number of elements in the array, which then changes the values for median, as well as first and last number.

    heres the code for that one

    Code:
    /*Header files that the program uses to interpret the code*/
    #include <stdlib.h>
    #include <stdio.h>
    
    #include <limits.h>
    
    
    /*The main function of the program*/
    
    
    main() {
    
    
    
      /* declare main program variables */
    
      
      char filename[256];
    
      FILE *in_fd;
      FILE *out_fd;
    
      int count = 0;           
    
      float next_number;
      float InputNumbers[100];
      int i=0;
      int j;
      int mid;
      float median;
      float temp;
      int max;
      float ascending[100];
      int Temp;
      char outputname[256];
      char order[256];
    
      
      
      
      
    
      /* get name of input file from user */
    
      
      printf("Enter input file name:");
    
      scanf("%s",filename);
    
    
    
    
    
      /* open file and print error message and exit on failure */
    
     
      if ((in_fd = fopen(filename, "r")) == 0) {
    
        fprintf(stderr, "File: %s Not Found!\n",filename);
    
        exit(0);
    
        }
    
        
       /*Asks user to name the ouput file, storing it in "outputname"*/
       
       printf("Enter the name of your output file:");
       scanf("%s", outputname);
       
       /*Creates output file, and opens it for writing*/
       
       out_fd=fopen(outputname, "w");
    
    
      /* this while loop reads numbers from the file until it is empty. */
      /* It stores these numbers in "InputNumbers" as "count" increments */
      /* through the array */
     
      
    
    
      while(fscanf(in_fd,"%f\n",&next_number)!=EOF) 
      {
    
        	count++;
        	InputNumbers[count]=next_number;
        	
        }
        
       max=count;
       count=0;
       
       
       /*Asks the user to enter either 1 or 2 in order to select an operation*/
       
       printf ("For ascending order, enter 1\nFor descending order, enter 2\n");
       
       scanf ("%d",&j);
       
       
       /* This "if" statement directs the program to the appropriate "for" statement */
       
       if (j==1){
       
       /*This is a bubble sort. The program increments through the array, */
       /*comparing each set of adjacent numbers. It swaps the numbers in  */
       /*order to satisfy the inequality*/
       
       	for (count=0;count<=max-1;count=count+1)
    	{
       		for(i=0;i<=max-1;i=i++)
       		{
       			if(InputNumbers[i]>InputNumbers[i+1])
     	 	 {
       			Temp=InputNumbers[i];
       			InputNumbers[i]=InputNumbers[i+1];
       			InputNumbers[i+1]=Temp;
       		}
       		}
       		
       		
    		
    	}
    	}
    
    
    /*This is also a bubble sort, but reversed in order to find the descending order*/
    
    else if (j==2)
    {
    
    	for (count=0;count<=max-1;count=count+1)
    	{
       		for(i=0;i<=max-1;i=i++)
       		{
       			if(InputNumbers[i]<InputNumbers[i+1])
     	 	 {
       			Temp=InputNumbers[i+1];
       			InputNumbers[i+1]=InputNumbers[i];
       			InputNumbers[i]=Temp;
       	}
       	}
       	
    	
    	}
    	}
    /*If the user enters a choice other than 1 or 2, the program informs the user */
    /*of his/her mistake*/
    
    else
    {
    printf("Not a valid choice");
    }
    
    
    /*If the number of elements in the array is even, then the program devides the max */
    /*by 2 and assigns it to "mid". It then adds the middle number ("mid") to the number */
    /*one less than the middle number, and then devide by 2*/
    
    if (max%2==0){
    
    mid=max/2;
    median=(InputNumbers[mid-1]+InputNumbers[mid])/2;
    
    
    /*This "for" loop increments through the now reordered array and places the values*/
    /*into the output file defined by the user. It then displays the other values within*/ 
    /*the display window*/
    
    for (i=0;i<=max;i++)
    	{
    	temp=InputNumbers[i];
    	fprintf(out_fd,"%f\n",temp);
    	}
    	printf("First number is %f\n",InputNumbers[0]);
    	printf("Last number is %f\n",InputNumbers[max]);
    	printf("The Median is %f\n",median);
    	}
    
    /*If the max is not even, then the program devides max by two and uses the value*/
    /*at that address as the median. Because mid is an "int" type rather than float,*/ 
    /*the number is rounded to the nearest integer. Because an odd integer devided by*/
    /*two always has a ".5", the number will round up to what is the appropriate median*/ 
    	
    else{
    mid=max/2;
    
    for(i=0;i<=max;i++)
    	{
    	temp=InputNumbers[i];
    	fprintf(out_fd,"%f\n", temp);
    	}
    	printf("First number is %f\n", InputNumbers[0]);
    	printf("Last number is %f\n", InputNumbers[max]);
    	printf("The Median is %f\n" ,median);
    	}
    	
    
       close(in_fd);
       close(out_fd);
       
      }
    also, feel free to correct any mistakes I make in the comments; those are graded as well, so if you notice something interpreted wrong, feel free to let me know!

    Thanks a ton!

  2. #2
    Registered User
    Join Date
    Apr 2009
    Posts
    8
    Well, i figured out my first problem. i learned a lot in fixing it, so maybe i'll figure out the other problem with the bubble sort

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,167
    Code:
     if(unit="%s","m"){
    3 things wrong.

    1. "=" is for assignment, "==" is for comparison.

    2. the "%s" thing (and other placeholders) is just for scanf/printf.

    3. you can't compare strings with "==" in C. You need to use the strcmp function.

    Code:
    if (strcmp(unit, "m") == 0) {
    http://www.cplusplus.com/reference/c...ng/strcmp.html

  4. #4
    Registered User
    Join Date
    Apr 2009
    Posts
    8
    ok

    well, I had it working with this

    Code:
    float number; 
    char unit[1];
    float m_km_ConvNum;
    float km_m_ConvNum;
    float M_ft_ConvNum;
    char* point[1];
    
    printf("Please enter the value that you wish to convert (including units):\n");
    
    printf("%f %c\n",number,*unit);
    
    if(*unit=='m'){
    
    	m_km_ConvNum=number*.001;
    
    	printf("%f Meters is equivalent to: %f Kilometers\n",number,m_km_ConvNum);
    
    }
    if(*unit=='K'){
    
    	km_m_ConvNum=number*1000;
    
    	printf("%f Kilometers is equivalent to: %f meters\n",number,km_m_ConvNum);
    
    }
    return (0);
    is there any plus to using the way you mentioned?

    also, when I went back and added a third if statement for another conversion it started giving me this:
    "0.000000 �"
    and then exits, no errors or anything

    any ideas?

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    for (count=0;count < max-1;count++)
    {
       for(i=0;i<max-1; i++)
       {
          if(InputNumbers[i] < InputNumbers[i+1])
          {
     	 Temp=InputNumbers[i];
       	 InputNumbers[i]=InputNumbers[i+1];
       	 InputNumbers[i+1]=Temp;
          }
       }  
    }
    
    Edit: changed it back to a descending sort, which is what you wanted.
    Your bubble sort is going one subscript too high when i is at the top of the array, and was set for descending sorting. I corrected it.

    I'm not used to that type of bubblesort, so no guarantee's.

    In general, avoid the " <= " and " >= " comparisons. C is made to not make such comparisons as common as in other programming languages. It will come back to bite you on the butt.
    Last edited by Adak; 04-04-2009 at 11:40 PM.

  6. #6
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,167
    is there any plus to using the way you mentioned?
    "Your way" only works for the first character in the string.

    In case you are not aware -
    Code:
    if(*unit=='m'){
    is the same as
    Code:
    if (unit[0] == 'm') {

    also, when I went back and added a third if statement for another conversion it started giving me this:
    "0.000000 �"
    and then exits, no errors or anything

    any ideas?
    Post the code.

  7. #7
    Registered User
    Join Date
    Apr 2009
    Posts
    8
    this is funny. I keep asking questions, figuring it out, but encountering another problem. Welcome to the world of programming i guess...

    so....I got rid of "0.000000 �", but now you have to type "end" to increment the program

    Code:
    #include <stdio.h>
    
    
    
    
    
    main() {
    
    
    
      /* declare main program variables */
    
    
    float number; 
    char unit[1];
    float m_km_ConvNum;
    float km_m_ConvNum;
    float M_ft_ConvNum;
    float f_M_ConvNum;
    
    
    printf("Please enter the value that you wish to convert (including units):\n");
    
    scanf("%f %c\n",&number,unit);
    
    if(*unit=='m'){
    
    
    	m_km_ConvNum=number*.001;
    
    	printf("%.3f Meters is equivalent to: %.3f Kilometers\n",number,m_km_ConvNum);
    
    }
    
    
    if(*unit=='K'){
    
    	km_m_ConvNum=number*1000;
    
    	printf("%.3f Kilometers is equivalent to: %.3f meters\n",number,km_m_ConvNum);
    
    }
    
    if(*unit=='M'){
    
    	M_ft_ConvNum=number*5280;
    
    	printf("%.3f Miles is equivalent to: %.3f Feet\n",number,M_ft_ConvNum);
    
    }
    
    if(*unit=='f'){
    
    	f_M_ConvNum=number*.00018939;
    
    	printf("%.3f Feet is equivalent to: %.3f Miles\n",number,f_M_ConvNum);
    
    }
    
    	return (0);	
    
    }
    also, for the other program, I've tried decreasing the amount of times the bubble sort passes through, but no luck. I keep getting things like this for the output:

    First number is 18070117044071811776512.000000
    Last number is 12.000000
    The Median is 0.000000

    so again, any help with that would be much appreciated.

    thanks!

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    unit is an address, already. It is not a pointer, and should have no * next to it.

  9. #9
    Registered User
    Join Date
    Apr 2009
    Posts
    8
    BTW, thanks cyberfish, i wasnt completely sure how that was working out.

    the "*" in front of unit, converts the char to int to allow it to be compared. And i guess since there is only one entry it uses that.

    is this correct thinking?
    thanks

  10. #10
    Registered User
    Join Date
    Apr 2009
    Posts
    8
    Adak, if i remove the *, I get:

    "warning:comparison between pointer and integer"

  11. #11
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    why are you making Unit an array of size 1?
    why not just make it a char?


    you get the warning because array names are treated as pointers to the first element of the array
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Please make unit a char!

    Also, if the sort is stuffed let's replace it with a known good one:

    Please don't change the algorithm on this:
    Code:
    for(i = 0; i < MaxArray - 1; i++)  {
    
       for(j = i + 1; j < MaxArray; j++)  {
          if(InputNumbers[i] < InputNumbers[j])
          {
     	 Temp=InputNumbers[i];
       	 InputNumbers[i]=InputNumbers[j];
       	 InputNumbers[j]=Temp;
          }
       }
    }
    Replace MaxArray with the number of numbers you have in the array.
    Last edited by Adak; 04-05-2009 at 01:08 AM.

  13. #13
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,167
    the "*" in front of unit, converts the char to int to allow it to be compared. And i guess since there is only one entry it uses that.

    is this correct thinking?
    A string in C is just an array of chars, with a nul character at the end ('\0'). An array can be converted to a pointer to the first element, and star (*) dereferences the pointer (returning the array's first element), which is the same as doing unit[0].

    If unit can only be one char, declare it as a char, not as an array, and use "==" to compare.

    If unit can be more than one char, declare it as a string (char array), and use strcmp() to compare.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Thrakity View Post
    BTW, thanks cyberfish, i wasnt completely sure how that was working out.

    the "*" in front of unit, converts the char to int to allow it to be compared. And i guess since there is only one entry it uses that.

    is this correct thinking?
    thanks
    Not at all. The * in front of the unit, is an error, and converts nothing at all.

    You get "away" with it here, because unit has only one char, I believe. A strict compiler should still throw an error, because a pointer is not the same thing as a name of a string array, although they are very similar.

    Still, you didn't declare unit as a pointer, and now you're saying "it's a pointer", and that should throw an error.

  15. #15
    Math wizard
    Join Date
    Dec 2006
    Location
    USA
    Posts
    582
    I also see another problem no one has apparently mentioned. You're working with integer values, but you're multiplying by 0.001. No wonder why you're getting zero. Use floats or doubles if you intend on working with fractions (and %f to display it it (%lf in the scanf function)). Another alternative is to divide by 1000, but fractional parts will be lost (making 6.8 become 6 rather than 7). I also see a typo - you've got "miles" stated in your string, even though you're apparently working with kilometers and meters instead of meters and miles. This is a harmless mistake though for normal use.
    High elevation is the best elevation. The higher, the better the view!
    My computer: XP Pro SP3, 3.4 GHz i7-2600K CPU (OC'd to 4 GHz), 4 GB DDR3 RAM, X-Fi Platinum sound, GeForce 460, 1920x1440 resolution, 1250 GB HDD space, Visual C++ 2008 Express

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple currency conversion program gone south!!
    By lildroopie in forum C Programming
    Replies: 1
    Last Post: 02-01-2009, 11:45 AM
  2. Conversion of pointers to functions
    By hzmonte in forum C Programming
    Replies: 0
    Last Post: 01-20-2009, 12:56 AM
  3. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM
  4. simple currency conversion problem
    By sweetgem in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2002, 12:41 PM
  5. Currency Conversion Program
    By kgraw21 in forum C Programming
    Replies: 5
    Last Post: 04-19-2002, 08:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21