struct - How to accept as one data type and store in a defined structure using functions in C? -
im having trouble, returning defined structure, function scan_sci suppose take input source string representing positive number in scientific notation, , breaks components storage in scinot_t structure. example input 0.25000e4
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct{ double mantissa; int exp; }sci_not_t; int scan_sci (sci_not_t *c); int main(void){ sci_not_t inp1, inp2; printf("enter mantissa in range [0.1, 1.0) exponent: "); scan_sci(&inp1); printf("enter second number same specifications above: "); scan_sci(&inp2); system("pause"); return 0; } int scan_sci (sci_not_t *c){ int status; double a; int b; status = scanf("%lf %d", &c->mantissa, &c->exp); = c->mantissa; b = c->exp; *c = pow(a,b); if (status == 2 && (c->mantissa >= 0.1 && c->mantissa < 1.0) ){ status = 1; }else{ printf("you did not enter mantissa in correct range \n"); status = 0; } return (status); } sci_not_t sum(sci_not_t c1, sci_not_t c2){ return c1 + c2; } sci_not_t product(sci_not_t c1, sci_not_t c2){ return c1 * c2; }
here's code reads console , puts value in scinot_t
there's no validation whatsoever.
it reads entire string using scanf 2 parts. first part %[^e]
reads char
that's not 'e'. reads 'e' , exponent.
the mantissa read string first , reparsed using sscanf.
#include <stdlib.h> typedef struct { double mantissa; int exp; }scinot_t; void scan_sci(scinot_t* s); int main(void){ scinot_t d; printf("enter value: "); scan_sci(&d); printf("mantissa %lf exponent %d\n", d.mantissa, d.exp); return 0; } void scan_sci (scinot_t *sn){ char inp1[20]; scanf("%[^e]e%d", inp1, &sn->exp); sscanf(inp1, "%lf", &sn->mantissa); return; }
to test mantissa range update main this:
int main(void){ scinot_t d; printf("enter value: "); (;;) { scan_sci(&d); if (d.mantissa>=0.1 && d.mantissa<=1.0) break; printf("you did not enter mantissa in correct range\nenter value: "); } printf("mantissa %lf exponent %d\n", d.mantissa, d.exp); return 0; }
Comments
Post a Comment