[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

demial points in arrays

I am reading keys pressed on a keypad into an array.  The numbers can vary from 0.01 to 500, with two decimal precision.  I am using the hex code 0X0A to signify a decimal point has been pressed.  I can see how to handle a number lthat begins with a decimal, or has no decimal..but what about soemthing like 206.33, or 0.03?  
while(keypress()!=0x0B); {  //not the # end signal       
           newkey[j]=keypress(); 
           j++;           
            }
           }
           
  if (newkey[0]==0x0A)   
  keytotal=0.1*newkey[1]*0.01+newkey[2]; 
     
  else 
  keytotal=newkey[0]+newkey[1]*10+newkey[2]*100;

Open in new window

0
rem2722
Asked:
rem2722
1 Solution
 
evilrixSenior Software Engineer (Avast)Commented:
Why don't you just get keypress() to return character representations of numbers and decimal point and then use sscanf() or atof() to do this conversion from string to float? You just need to make sure newKey is null terminated.

http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html
http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html

Would this work?

-Rx.
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
	char newKey[] = "206.33"; // Assume this is what's returned by keypress
	float keytotal1 = 0;
	float keytotal2 = 0;
 
	sscanf(newKey, "%f", &keytotal1); // You could do this...
	keytotal2 = (float) atof(newKey); // ...or this
 
  return 0;
}

Open in new window

0
 
Infinity08Commented:
Here are two alternatives :
/* alternative 1 : calculating as the key presses come in */
 
unsigned char key = 0x00;
double value = 0.0;
int dec_cnt = -1;
while ((key = keypress()) != 0x0B) {
  if ((dec_cnt >= 0) || (key == 0x0A)) ++dec_cnt;
  if (key < 0x0A) {
    value = (value * 10.0) + ((double) key)
  }
}
while (dec_cnt--) {
  value /= 10.0;
}
 
 
/* alternative 2 : make use of sscanf */
 
unsigned char key = 0x00;
char value_str[32] = { 0 };
int i = 0;
double value = 0.0;
while ((key = keypress()) != 0x0B) {
  if (key == 0x0A) value_str[i++] = '.';
  else if (key < 0x0A) value_str[i++] = '0' + key;
}
sscanf(value_str, "%f", &value);

Open in new window

0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now