Thread: me lamer need help- fprintf

1. me lamer need help- fprintf

Hi everyone

well I have a new problem that makes me go crazy.

let me explain this code

enter n, steps x1

example:
n=6 ; x1=1.25 ---->1.25 2.5 3.75 5 6.25 7.5
calculate yi= xi^2 + 3xi +3
and fprintf to test.dat.

Then use the data to draw with gnuplot on screen, but thats another story.
Code:
```#include<stdio.h>
#include<stdlib.h>

int main (void)
{

double *y, *x, xi, x1;
int i,n;
FILE *fp;
printf(" n-->"); scanf("%f",&n);
printf("x1-->"); scanf("%f", &x1);
y=   malloc( n*sizeof(double) );
x=   malloc( n*sizeof(double) );
fp=fopen("test.dat", "w");
xi=x1;
for (i=0; i<n; i++)
{
y[i]= xi*xi - 3*xi +3;
x[i]= xi;
xi= xi+x1;
fprintf(fp,"%f  %f\n",y[i], x[i]);
fflush(fp);

}

fclose(fp);
free(y);
free(x);
return 0;
}```
result endless loop, huge growing .dat file 14Meg
and this
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
-1.#QNAN0 -1.#QNAN0
.
.

2. Here are the offending lines:

printf(" n-->"); scanf("%f",&n);
printf("x1-->"); scanf("%f", &x1);

In the first scanf the variable 'n' is of type integer but you try and read it as a floating-point number. You need %d or %i instead of %f. In the second x1 is a double floating-point. You try to read it with a single floating-point specifier. You need %lf for long float.

3. > printf(" n-->"); scanf("%f",&n);
> printf("x1-->"); scanf("%f", &x1);
Get a compiler which can diagnose scanf abuse
First one should be %d, since n is an integer
Second one should be %lf, because x1 is a double
Both values will be junk in your code.

Also, since you calculate and use x[i] and y[i] in the same loop iteration, there is no actual need to store these values in an array.

4. silly me. THX!!!!!

well I use lcc win32, and it didnīt give a warning ar an error. Any suggestion?

5. No idea - read the manual page for whatever warnings it has, and turn them all on.

gcc for example has -Wall which checks a whole bunch of stuff

Popular pages Recent additions