hello,

I think I have a rather straightforward problem, but I'm relatively new to C. I have an input file that looks like this:

0.682448 0.53791 0.61727 0.48714
0.297144 0.29688 0.40549 0.68233
0.426100 0.62057 0.25095 0.54782
0.673007 0.51040 0.25476 0.35149
0.641339 0.49815 0.54557 0.42673
0.268030 0.38949 0.48841 0.56580
...

I need to compute x=p*log(p), where p corresponds to one element in my array, say 0.682448. and then, I need to add, let's say, the first 8 'x' values (the first two rows). I need to send that value to an external file, and keep doing it until I reach the end of the file.

I'm not sure how to import the individual float values and how to advance to the next line and how to stop after 2 lines and sum all the values up and then resume the process. I can have the external file formated so that the individual values are either separated by a single space or by a TAB.

I appreciate any suggestions.

r.

you can use fscanf("%f", ...) to input the values from the file. Use a counter integer to count 8 fscnaf().

int i;
float nums[8];
FILE* in = fopen("filename.txt");
for(i = 0; i < 8; i++)
{
    fsscanf("%f", &nums[i]);
}

terrific, that worked like a champ. thanks.

one more question, though: in mathematics, the difference between log and ln is that log uses base 10 and ln uses base e. I need to use ln base e, however, it looks like the 'math.h' does not have it in the form that I'd expect. do you know how I can get the ln base e?

this is the working code, however, it uses log base 10

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

main(void)
{
  FILE *pFile1;
  FILE *pFile2;
  int i,a;
  float p[32], x[32], sum;

  pFile1 = fopen ("in2.txt","r");  
  pFile2 = fopen ("out2.txt","w");  

  for(a = 0; a < 6; a++)
  {
  sum=0.0;

    for(i = 0; i < 32; i++)
    {
      fscanf(pFile1, "%f", &p[i]);
    }

    for(i = 0; i < 32; i++)
    {
      x[i]=p[i]*log(p[i]);
    }

    for(i = 0; i < 32; i++)
    {
      sum=sum+x[i];
    }

    fprintf(pFile2,"%f", sum);
    fprintf(pFile2, "\n");
  }

  fclose (pFile1);  
  fclose (pFile2);  

  return(0);
}

in <math.h>

"log" is the natural logarithm (base e)

"log10" is the base10 logarithm


.

Ya, and for any other bases you have the formula

log a ( base b ) = log a ( base c ) / log b ( base c )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.