Thread: modifying help plz ( int to float )

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    36

    modifying help plz ( int to float )

    can someone please help me modify this program to read floats instead of ints?

    im getting lost in my code :S

    if this is not a quick fix, i guess i just have to follow each data type being passed into each function always keeping track of the data types being sent/received?


    Code:
    #include <stdio.h>
    
    #define YESNUM              1
    #define NONUM               0
    #define MAX_NUM_PROCESSED   20
    #define MAX_LINE_LEN        127
    
    
    int GetArray(int [], int);
    int GetInt(int *);
    int StoI(const char *, int *);
    void BSort(int [], int);
    void DumpArray(const int [], int);
    
    
    
    int main(void)
    {
    	int intArray[MAX_NUM_PROCESSED];
    	int numRead;
    
    	printf("This program stops reading numbers after &#37;d ", MAX_NUM_PROCESSED);
    	printf("values\nor if EOF is encountered.\n\n");
    
    	numRead=GetArray(intArray, MAX_NUM_PROCESSED);		// Load the integer array
    
    	printf("Before sort:\n");
    	DumpArray(intArray, numRead);						// Print the pre-sorted contents
    	BSort(intArray, numRead);							// Sort them
    
    	printf("After sort:\n");
    	DumpArray(intArray, numRead);						// Print the sorted contents
    
    	return(0);
    }
    
    
    
    /*****************************************************************************
     * FUNCTION:	GetArray
     *
     * DESCRIPTION:	This function loads the integers read into an integer array.
     *				It prints a message informing if an integer can be loaded
     *				into the array.
     * 
     * INPUT:		numArray		- (int []) the address of the integer array
     *				maxNumAllowed	- (int)    the maximum number of integers
     *										   allowed
     *
     * OUTPUT		numArray		- (int []) On completion, this array is 
     *										   modified
     *
     * RETURNS:		an integer indicating the actual number of integers read
     *				and loaded into the arra
     *
     *****************************************************************************/
    int GetArray(int numArray[], int maxNumAllowed)
    {
    	int arrayIndex=0;
    	int status;
    
    
    	while (arrayIndex<maxNumAllowed &&
             (status=GetInt(&numArray[arrayIndex]))!=EOF) {
    
    		if (status==YESNUM)
    			printf("%d has been accepted\n", numArray[arrayIndex++]);
    		else
    			printf("Invalid number detected, re-enter\n\a");
    	}
    
    	if (arrayIndex>=maxNumAllowed)
    		printf("Maximum number of inputs reached\a\n\n");
    
    	return(arrayIndex);
    }
    
    
    
    
    
    /*****************************************************************************
     * FUNCTION:	GetInt
     *
     * DESCRIPTION:	This function reads an integer value from the computer
     *				standard input.
     *
     * INPUT:		pnum - (int *) the address of an integer variable
     *
     * OUTPUT:		pnum - (int *) on completion, the integer pointed by
     *							   this pointer will be modified.
     *
     * RETURNS:		a tri-state status code
     *					EOF    - on end of file
     *					YESNUM - a valid integer read
     *					NONUM  - an invalid data detected
     *		
     *****************************************************************************/
    int GetInt(int *pnum)
    {
    	char buf[MAX_LINE_LEN+1];
    
    	printf("Enter a number:  ");
    	return( gets(buf)==NULL ? EOF : StoI(buf, pnum) );
    }
    
    
    
    
    
    /*****************************************************************************
     * FUNCTION:	StoI
     *
     * DESCRIPTION:	This function takes an ASCII-Z and converts it to an integer.
     *				it is similar to the standard runtime library function atoi
     *
     * INPUT:		but  - (const char *) the address of an ASCII-Z
     *				iPtr - (int *) the address of an integer variable used to
     *							   store the converted value.
     *
     * OUTPUT:		iPtr - (int *) On completion, the integer variable pointed
     *							   by this pointer is modified.
     *
     * RETURNS:		A binary status indicating the successfulness of the conversion
     *					NONUM  - bad conversion
     *					YESNUM - good conversion
     *
     *****************************************************************************/
    int StoI(const char *buf, int *iPtr)
    {
    	int	divisor=10;
    	int signBit=1;
    	int arrayIndex=0;
    	int conversionStatus;
    
    
    	while (buf[arrayIndex]==' ')		// Strips leading spaces
    		arrayIndex++;
    
    	// Remember sign 
    	if (buf[arrayIndex]=='+' || buf[arrayIndex]=='-')
    		signBit= (buf[arrayIndex++]=='-') ? -1 : 1;
    
    
    	*iPtr=0;							// Initialize the integer variable
    
    	// This loop exploits the standard decomposition of an integer
    	// For example, 123 = 1 * 10^2 + 2 * 10^1 + 3 * 10^0, etc.
    	// To convert a single character digit to its numeric value,
    	// simply subtract '0' from it.  This is exploitation of its
    	// ASCII table behaviour.
    	while(buf[arrayIndex]>='0' && buf[arrayIndex]<='9')
    		*iPtr= *iPtr*10 + (buf[arrayIndex++]-'0');
    
    
    	if (buf[arrayIndex]=='\0') {
    		*iPtr *= signBit;
    		conversionStatus=YESNUM;
    	}
    	else
    		conversionStatus=NONUM;
    
    	return(conversionStatus);
    }
    
    
    
    
    
    /*****************************************************************************
     * F........ION:	BSort
     *
     * DESCRIPTION:	This function uses the basic bubble sort algorithm to sort
     *				an array of integers.
     *	
     * INPUT:		numArray  - (int []) base address of the integer array to sort.
     *				arraySize - (int) the actual number of elements in the array.
     *
     * OUTPUT:		numArray - (int []) this array is modified on function 
     *                                  completion
     *
     * RETURNS:		None
     *
     *****************************************************************************/
    void BSort(int numArray[], int arraySize)
    {
    	int i,
    		j;
    	int temp;
    
    	for (i=0; i<arraySize-1; i++)
    		for (j=arraySize-1; j>i; j--)
    			if (numArray[i]>numArray[j]) {
    				temp=numArray[i];
    				numArray[i]=numArray[j];
    				numArray[j]=temp;
    			}
    }
    
    
    
    
    
    /*****************************************************************************
     * FUNCTION:	DumpArray
     *
     * DESCRIPTION:	This function prints the contents of an integer array
     *
     * INPUT:		numArray  - (int []) base address of the array to be dumped
     *				arraySize - (int) the actual number of elements in the array.
     *
     * OUTPUT:		None
     *
     *****************************************************************************/
    void DumpArray(const int numArray[], int arraySize)
    {
    	int arrayIndex;
    
    	printf("The list is:\n\n");
    	for (arrayIndex=0; arrayIndex<arraySize; arrayIndex++)
    		printf("%#3d:  %d\n", arrayIndex+1, numArray[arrayIndex]);
    }
    Last edited by sh4k3; 06-26-2007 at 07:08 PM.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Oh, come on! You have such a nice code, sure you can make this little change.

    Yes, change appropriate ints to floats and don't forget I/O format flags.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    36
    ive been staring at this for the past hour and cant seem to figure it out..
    i keep running circles i think ...

    maybe i shouldnt have eaten so many burritos for lunch
    i think the beans are affecting my ability to concentrate

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    This isn't that difficult. Make a new copy of the source code, and start hacking it up. Change the declarations and the format flags as was already stated.

    If you can't do this, I am seriously in doubt you wrote the code.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > If you can't do this, I am seriously in doubt you wrote the code.
    I'd have to agree, it looks like teachers code given to the students to convert.

    However, said "teacher" needs a damn good slapping for using gets().

    It also seems like the language filter had a go at one of the comments
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jun 2007
    Posts
    36
    ok... i did most of the dirty work, but now im getting some undesired output.

    when i enter in an integer, the program converts it to a float...

    but the problem is now, when i enter in a float, for ex. 2.1... the program converts it to 1.2

    and if i enter in a float with more than one digit before the decimal, then i get a whole bunch of undesired outputs.

    here is my code:

    Code:
    #include <stdio.h>
    
    #define YESNUM              1
    #define NONUM               0
    #define MAX_NUM_PROCESSED   20
    #define MAX_LINE_LEN        127
    
    
    int GetArray(float [], int);
    int GetInt(float *);
    int StoI(const char *, float *);
    void BSort(float [], int);
    void DumpArray(const float [], int);
    
    
    
    int main(void)
    {
    	float intArray[MAX_NUM_PROCESSED];
    	int numRead;
    
    	printf("This program stops reading numbers after %d ", MAX_NUM_PROCESSED);
    	printf("values\nor if EOF is encountered.\n\n");
    
    	numRead=GetArray(intArray, MAX_NUM_PROCESSED);		// Load the integer array
    
    	printf("Before sort:\n");
    	DumpArray(intArray, numRead);						// Print the pre-sorted contents
    	BSort(intArray, numRead);							// Sort them
    
    	printf("After sort:\n");
    	DumpArray(intArray, numRead);						// Print the sorted contents
    
    	return(0);
    }
    
    
    
    /*****************************************************************************
     * FUNCTION:	GetArray
     *
     * DESCRIPTION:	This function loads the integers read into an integer array.
     *				It prints a message informing if an integer can be loaded
     *				into the array.
     * 
     * INPUT:		numArray		- (float []) the address of the integer array
     *				maxNumAllowed	- (int)    the maximum number of integers
     *										   allowed
     *
     * OUTPUT		numArray		- (float []) On completion, this array is 
     *										   modified
     *
     * RETURNS:		an integer indicating the actual number of integers read
     *				and loaded into the arra
     *
     *****************************************************************************/
    int GetArray(float numArray[], int maxNumAllowed)
    {
    	int arrayIndex=0;
    	int status;
    
    
    	while (arrayIndex<maxNumAllowed &&
             (status=GetInt(&numArray[arrayIndex]))!=EOF) {
    
    		if (status==YESNUM)
    			printf("%f has been accepted\n", numArray[arrayIndex++]);
    		else
    			printf("Invalid number detected, re-enter\n\a");
    	}
    
    	if (arrayIndex>=maxNumAllowed)
    		printf("Maximum number of inputs reached\a\n\n");
    
    	return(arrayIndex);
    }
    
    
    /*****************************************************************************
     * FUNCTION:	GetInt
     *
     * DESCRIPTION:	This function reads an integer value from the computer
     *				standard input.
     *
     * INPUT:		pnum - (float *) the address of an integer variable
     *
     * OUTPUT:		pnum - (float *) on completion, the integer pointed by
     *							   this pointer will be modified.
     *
     * RETURNS:		a tri-state status code
     *					EOF    - on end of file
     *					YESNUM - a valid integer read
     *					NONUM  - an invalid data detected
     *		
     *****************************************************************************/
    int GetInt(float *pnum)
    {
    	char buf[MAX_LINE_LEN+1];
    
    	printf("Enter a number:  ");
    	return( gets(buf)==NULL ? EOF : StoI(buf, pnum) );
    }
    
    
    
    /*****************************************************************************
     * FUNCTION:	StoI
     *
     * DESCRIPTION:	This function takes an ASCII-Z and converts it to an integer.
     *				it is similar to the standard runtime library function atoi
     *
     * INPUT:		but  - (const char *) the address of an ASCII-Z
     *				iPtr - (float *) the address of an integer variable used to
     *							   store the converted value.
     *
     * OUTPUT:		iPtr - (int *) On completion, the integer variable pointed
     *							   by this pointer is modified.
     *
     * RETURNS:		A binary status indicating the successfulness of the conversion
     *					NONUM  - bad conversion
     *					YESNUM - good conversion
     *
     *****************************************************************************/
    int StoI(const char *buf, float *iPtr)
    {
    	int divisor=10;
    	int signBit=1;
    	int arrayIndex=0;
    	int conversionStatus;
    
    	while (buf[arrayIndex]==' ')		// Strips leading spaces
    		arrayIndex++;
    
    	// Remember sign 
    	if (buf[arrayIndex]=='+' || buf[arrayIndex]=='-')
    		signBit= (buf[arrayIndex++]=='-') ? -1 : 1;
    
    
    	*iPtr=0;							// Initialize the integer variable
    
    	// This loop exploits the standard decomposition of an integer
    	// For example, 123 = 1 * 10^2 + 2 * 10^1 + 3 * 10^0, etc.
    	// To convert a single character digit to its numeric value,
    	// simply subtract '0' from it.  This is exploitation of its
    	// ASCII table behaviour.
    	//int isDecimal = 0;
    	while(buf[arrayIndex]>='0' && buf[arrayIndex]<='9' && buf[arrayIndex] != '\0')
    	{
    
    		if( buf[arrayIndex]>='0' && buf[arrayIndex]<='9' && buf[arrayIndex]!='.')
    		{
    			*iPtr= *iPtr*10 + (buf[arrayIndex++]-'0'); // turning char into int... taking ascii value and subtracting char 0, to get a numeric value
    		}
    	
    		if(buf[arrayIndex]=='.')
    		{
    			arrayIndex++;
    		
    			while(buf[arrayIndex]>='0' && buf[arrayIndex]<='9' && buf[arrayIndex] !='\0')
    			{
    					*iPtr = *iPtr/10 + (buf[arrayIndex++]-'0');
    			}
    				
    		}
    	}
    	
    
    	if (buf[arrayIndex]=='\0') {
    		*iPtr *= signBit;
    		conversionStatus=YESNUM;
    	}
    	else
    		conversionStatus=NONUM;
    
    	return(conversionStatus);
    }
    
    
    /*****************************************************************************
     * F........ION:	BSort
     *
     * DESCRIPTION:	This function uses the basic bubble sort algorithm to sort
     *				an array of integers.
     *	
     * INPUT:		numArray  - (float []) base address of the integer array to sort.
     *				arraySize - (int) the actual number of elements in the array.
     *
     * OUTPUT:		numArray - (float []) this array is modified on function 
     *                                  completion
     *
     * RETURNS:		None
     *
     *****************************************************************************/
    void BSort(float numArray[], int arraySize)
    {
    	int i,j;
    	float temp;
    
    	for (i=0; i<arraySize-1; i++)
    		for (j=arraySize-1; j>i; j--)
    			if (numArray[i]>numArray[j]) {
    				temp=numArray[i];
    				numArray[i]=numArray[j];
    				numArray[j]=temp;
    			}
    }
    
    
    /*****************************************************************************
     * FUNCTION:	DumpArray
     *
     * DESCRIPTION:	This function prints the contents of an float array
     *
     * INPUT:		numArray  - (float []) base address of the array to be dumped
     *				arraySize - (int) the actual number of elements in the array.
     *
     * OUTPUT:		None
     *
     *****************************************************************************/
    void DumpArray(const float numArray[], int arraySize)
    {
    	int arrayIndex;
    
    	printf("The list is:\n\n");
    	for (arrayIndex=0; arrayIndex<arraySize; arrayIndex++)
    		printf("%#3d:  %f\n", arrayIndex+1, numArray[arrayIndex]);
    }

  7. #7
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    AHH! Use pastebin please.

  8. #8
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    1. do not use gets - use fgets (see faq)
    2. your conversion after the '.' is encountered is wrong

    1.2 is not 1/10.0 + 2
    it is (1* 10.0 + 2) / 10.0

    32.45 = (((3*10.0 +2)*10.0 + 4)*10.0+5)/100.0

    BTW why not to use strtod?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    That's not bubble sort you've implemented there. "Bubble Sort" is stable.
    What you've written is what some would call "Simple Sort" and is not stable.

    For your purposes however, it will also do just fine.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Don't forget to change also: variable and function names, and comments. float intArray is rather scary...
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  11. #11
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    A similar program to do the work is the following. This is made for integers not float numbers, but i want to give you the idea of thinking what i did and if you get it right you will get it work out.

    PHP Code:
    [code]

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

    //Reads a string from input, the string should be a number.

    intGetInt(int Sizeint *Asizeint *Sign)
    {
          if(
    Size 0)
          {
                  
    //For loop.
                  
                  
    int i;
                  
    int j 0;
                  
    char c;
                  
    int sign 1;
                  
    int number 0;
                  
                  
    //Buffer to hold data.
                  
                  
    char *buffer NULL;
                  
                  
    //Array to hold the return digits.
                  
                  
    int *NULL;
                  
                  
    //Work it.
                  
                  
    buffer = (char *)malloc(sizeof(char) * Size);
                  if(
    buffer == NULL)
                  {
                            
    printf("Error no memory available.\n");
                            return 
    NULL;
                  }
                  
                  if(
    fgets(bufferSizestdin) == NULL)
                  {
                                    
    printf("Error, in fgets().\n");
                                    return 
    NULL;
                  }
                  if(
    buffer[strlen(buffer) - 1] == '\n')
                                           
    buffer[strlen(buffer) - 1] = '\0';
                  
                                           
                  
    //Loop now to get the number.
                  
                  
    for(0strlen(buffer); i++)
                  {
                        
    buffer[i];
                        if(!
    && (== '+' || == '-'))
                              
    sign = (== '+') ? : -1;
                        if(
    isalpha(c) || isspace(c))
                        {
                             
    printf("Error in input in place %d, incorrect symbol %c.\n"ic);
                             break;
                        }
                        if(
    isdigit(c))
                        {
                                      
    //Use of realloc here.
                                      
                                      
    number '0';
                                      
    = (int *)realloc(Asizeof(int));
                                      if(
    A)
                                           
    A[j++] = number;
                                      else
                                          break;
                        }
                  }
                  if(
    == strlen(buffer) && j)
                  {
                       *
    Asize j;
                       *
    Sign sign;
                       
    free(buffer);
                       return 
    A;
                  }
                  else
                  {
                      *
    Asize 0;
                      
    free(buffer);
                      
    free(A);
                      return 
    NULL;
                  }
          }
          else
          return 
    NULL;
    }
                      
    void DumpArray(int *Aint Asize)
    {
         if(
    A)
         {
              
    int i;
              for(
    0Asize && printf(!= Asize -"%d " "%d\n" A[i]); i++);
         }
    }
    int GetNumberFromArray(int *Aint Asizeint Sign)
    {
        if(
    A)
        {
             
    //Return Value.
             
             
    int n 0;
             
             
    //Index.
             
             
    int i 0;
             
    int j 0;
             
             
    //BASE
             
             
    int BASE  1;
             
             
    //Start from the end of the array, advance base * 10 and go on.
             
             
    for(Asize-1>=0i--)
             {
                   
    += A[i] * BASE;
                   
                   
    BASE *= 10;
             }
             if(
    0)
                  return 
    Sign;
             else
                 return -
    1;
        }
        else
            return -
    1;
    }   
    int main(int argcchar *argv[])
    {
        
    int Asize 0;
        
    int Sign 0;
        
    int n 0;
        
    int *NULL;
        
    printf("Enter the number:");
        
    GetInt(1024, &Asize, &Sign);
        
    DumpArray(AAsize);
        
    printf("\n\n");
        
    GetNumberFromArray(AAsizeSign);
      
        
    printf(!= -"Number is: %d\n" "Error in GetNumberFromArray {Check it}\n"n);
      
        
    system("PAUSE");    
        return 
    0;
    }

    [/
    code

  12. #12
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Bokarinho don't do that, and use pastebin for goodness sake!

    * I don't like scrolling

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Drawing Program
    By Max_Payne in forum C++ Programming
    Replies: 21
    Last Post: 12-21-2007, 05:34 PM
  3. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  4. Replies: 2
    Last Post: 03-24-2006, 08:36 PM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM