0

I wrote a piece of code for queuing system for a simulation. And I need to print some values to a txt file after compiling the code. I wrote the code for writing to files but although it creates the file, it does not print the values to my text file. If you can help I will appriciate. Here is the piece of code that I have...

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

int main()
{
float rho_start ; // start value of the utilization factor 
float rho_end ; // end value of the utilization factor
float rho_step ; // step value of the utilization factor
float lambda ; // ratio of customers and time
float N ; // mean number of customers in the system
float Q ; // mean number of customers in queue
float res_time ; // response time
float mu ; // service rate , assuming mu = 10 customers/s for this assignment
float i ; // for the loop

printf("Please enter the start value of the rho : ");
scanf("%f",&rho_start);

printf("Please enter the end value of the rho : ");
scanf("%f",&rho_end);

printf("Please enter the step value of the rho : ");
scanf("%f",&rho_step);

printf("Please enter the mu : ");
scanf("%f",&mu);

printf("RHO \t\t N \t\t Q \t\t RT \n");
printf("--- \t\t --- \t\t --- \t\t --- \n");
for( i = rho_start ; i < rho_end ; i = i + rho_step)
{
    N = i/(1-i) ;
    lambda = i * mu ;
    Q = (i*i)/(1-i) ;
    res_time = N/lambda ;
    printf("%.3f \t\t %.3f \t\t %.3f \t\t %.3f \n", i , N , Q , res_time);
}

    FILE * f1;

    f1 = fopen("sample.txt","w");

    if( rho_step == 0.1 )
    {   

        for(i = rho_start ; i < rho_end ; i = i + rho_step)
        {
            N = i/(1-i) ;
            fprintf(f1 , "%.3f \t\t %.3f \n" , i , N);

        }
    }



    if( f1 == NULL ) 
    {       
    printf("Cannot open file.\n");
    exit(1);
    }

    fclose(f1);




return 0;

}

pjs
  • 18,696
  • 4
  • 27
  • 56
erengsgs
  • 43
  • 1
  • 1
  • 4
  • Oddly enough, this is a frequently asked question about floating point! `if(rho_step == 0.1)` will never be true, because floating point numbers are not mathematical real numbers. – zwol Nov 19 '16 at 00:34
  • Also, your `if (f1 == NULL)` check should be immediately after the call to `fopen`, and `printf("Cannot open file.\n")` should read `printf("Cannot open %s: %s\n", "sample.txt", strerror(errno));` (You'll need to include string.h and errno.h if you aren't already.) This isn't your _current_ problem but it is very likely to be your problem in the future. – zwol Nov 19 '16 at 00:35
  • And a final word of warning: when you put spaces on the inside of parentheses (`if( rho_step == 0.1 )` instead of `if (rho_step == 0.1)`) you make the baby Jesus cry. You don't want to make the baby Jesus cry, do you? – zwol Nov 19 '16 at 00:36

0 Answers0