Funkcja atof.

0

Otoz mam na zadanie zrobic funkcje na zasadzie dzialania funkcji "atof".

Czyli np jesli mam podane char[6]="1.567"; to zeby zamienil ta liczbe na double a=1.567; Oczywiscie bez uzycia tej funkcji!
oraz drugi program ktory zamieni z double na char.
Dodam iz uzywam Visual Basica. Nie bardzo wiem jak sie za to wziac ;/ Nie wiem czy dobrze zamiescilem ten temat, jednak dziekuje z gory za pomoc ;)

0

Podpucha.

0

istnieje gotowe funkcje strtod, strtof, strtold

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

double str2d(char* nptr,char** endptr){
  double d=0.0;
  char* s=nptr;
  int sgn=(*s=='-');
  if(*s=='-' || *s=='+')s++;
  int noerr=1;
  double i=0.0;
  do{
    if((noerr=(*s<='9')&&(*s>='0'))){
      d*=10;
      d+=(*s-'0');
      i*=10;
      s++;
    }else if(*s=='.'){
      i=1.0;
      s++;
      noerr=1;
    }
  }while(*s && noerr);
  if(i>0.0)d/=i;
  if(sgn)d=-d;
  if(endptr)*endptr=s;
  return d;
}

int main(){
  char* c;
  double d=str2d("-128.23",&c);
  printf("%f %d %c\n",d,*c,*c);
  d=str2d("+128.23",&c);
  printf("%f %d %c\n",d,*c,*c);
  d=str2d("0.23",&c);
  printf("%f %d %c\n",d,*c,*c);
  d=str2d("-.23",&c);
  printf("%f %d %c\n",d,*c,*c);
  d=str2d("-.2a3",&c);
  printf("%f %d %c\n",d,*c,*c);
  return 0;
}

w drugą manke jest równie prosto.

1 użytkowników online, w tym zalogowanych: 0, gości: 1