-1

edit-

So I understand that there is no solution to this problem. Does anyone know a function in C that returns the 31-38 index from the array(str)?

Hey i have a problem with strtof function and i cant find a solution to the problem on the Internet, Can anyone help please?

here a simple function:

float getCord(int placeOnArray, char str[80]){
   char str2[7];
   for (int i=placeOnArray ;i<placeOnArray+7;i++){
      str2[i-placeOnArray]=str[i];
   }
   float f1;
   f1=strtof(str2,NULL);
   return f1;

    }

the input- str= ATOM 1 N ASN A 1 -4.890 -12.296 -15.280 1.00 30.36 N , place on array=31

The desired result: -4.890 ,the returned result: -4.88999987

papi
  • 227
  • 1
  • 4
  • 11

3 Answers3

1

strtof works as expected:

Consisder this little program:

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

int main () 
{
  float f = strtof("4.890", NULL);
  printf("%10.10f\n", f);
} 

The output is:

4.8899998665

There is no exact representation of 4.890 in floating point. You need to read this SO article:

Also your getCord function is wrong:

This is a simpler and correct alternative:

float getCord(int placeOnArray, char str[]) {
  return strtof(str + placeOnArray, NULL);
}

There is no need to extract the string representing the number, you can directly scan for the number in the original string. strtof will stop at the first character different from 0-9 and '.'. Change the first line in the program above to float f = strtof("4.890 ", NULL);, the output will be the same.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

desired result: -4.890 ,the returned result: -4.88999987

There will always be some error in a floating point operation. This is expected and should be taken care of by the programmer.

That is why you cannot use f1==f2 for floating point numbers. You need to check that the numbers are within the given error range. For floats this is FLT_EPSILON

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
0
//
//  main.c
//
//
//  Created by myhaspl on 2018/10/22.
//   myhaspl@myhaspl.com.
//   https://dmyhaspl.github.io/
//

#include <stdlib.h>
#include <stdio.h>
char mytoken[10];
char* getCord(int placeOnArray, char mystr[80]){
    const char s[2] = " ";
    char str2[7];

    char* token=mytoken;
    for (int i=placeOnArray ;i<placeOnArray+7;i++){
        str2[i-placeOnArray]=mystr[i];
    }
    strcpy(mytoken,strtok(str2, s));
    printf("%s\n",mytoken);
    return mytoken;
}
int main(){
    char str[80] = "ATOM 1 N ASN A 1 -4.890 -12.296 -15.280 1.00 30.36 N";
    char* token=getCord(17,str);
    printf("%s\n",token);
    float number=atof(token);
    printf( "%f\n", number );
    return 0;
}

-4.890
-4.890
-4.890000
myhaspldeep
  • 226
  • 2
  • 7