1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

help pleas with program

Discussion in 'C' started by nzrusty, Dec 12, 2006.

  1. nzrusty

    nzrusty New Member

    Dec 12, 2006
    Likes Received:
    Trophy Points:
    Im trying to work out the total values of a table, which i have read from a file

    x y
    1.0 2.876
    2.6 4.234
    3.7 8.874
    4.5 7.698
    6.0 9.932

    I want to work out the total values of x, i.e sum of.

    How would i implement this, please. thanks, here is what i have so far, ive tried to work out the sum using a loop, do i need to use a link list and if so how do i do this, please. Any help will be greatly appreicated. Thanks
    #include <stdio.h>
    #include <math.h>
    int main(void)
    	char line [101];
    	char *line_ptr;
    	double x, y;
    	int no_values=-1;
    	double sum_x;
    	int i=0;
    	FILE *input_stream;
    	if ((input_stream=fopen("test_data.dat", "r")) != NULL)
    		while ((line_ptr=fgets(line, sizeof(line), input_stream))!= NULL)
    			if ((sscanf (line, "%d %d", &x, &y)) != 2)
    				fprintf (stdout, "%s\n", line);
    	fprintf(stdout, "\n\n\n\nno_values: %d\n", no_values);
    	for (i=0; i<=no_values; i++)
    		sum_x= x;
    	fprintf(stdout, "\n\n\n\nsum_x: %lf\n", sum_x);
    Last edited by a moderator: Dec 13, 2006
  2. DaWei

    DaWei New Member

    Dec 6, 2006
    Likes Received:
    Trophy Points:
    Semi-retired EE
    Texan now in Central NY
    Home Page:
    It appears you didn't read the "Hints before you make a post" thread. That's rude, because you have posted code that has lost its formatting and is difficult to read; yet, you want voluntary help. Please rectify that oversight. Furthermore, you haven't said what your exact problem is with your code. We are not mind readers. Information is key. You can get some from error messages, you can get some from your debugger, you can get some by sprinkling output statements in the area where you are having problems.

    No, you don't need a linked list; an array would do just fine, if you plan to sum them AFTER the read, as you're doing now. You could also sum them during the read, if you had no further use for the individual components. You won't get a sum with "sum_x = x". That will just replace the value of sum_x with the value of x each time. You need to use "sum_x += x", which is shorthand for "sum_x = sum_x + x." In any event, as mentioned above, the x has to be the input series, which means do it as you read, or store the entire series in an array.

Share This Page