/********************* raw2latex.c ******************* * * * Solution of Problem 4 of Homework Group 1. * * Problem: (in Hungarian) * * http://www.phy.bme.hu/~balogh/szamszim2011/#03het * * * ***************************************************** * L\'aszl\'o Balogh, blaci947@yahoo.co.uk * * Sep 20 2011 * *****************************************************/ // buffer size for 1 line of input (10k should be enough) #define MAXLINE 10000 #include #include char* double2str(double d_, char* str_); int main(void){ int a; // 1st field in the input file double b, c; // 2nd and 3rd field in the input file char bstr[100], cstr[100]; // the scientific notation of b and c char line[MAXLINE]; // temporary storage for 1 line of input // This code fragment was reused from the class. // SRC: http://www.phy.bme.hu/~balogh/szamszim2011/src/1/pow.c // read the first line from the input: fgets(line, MAXLINE, stdin); // process until the end of the input file: while (!feof(stdin)) { if ( sscanf(line, "%d %lf %lf", &a, &b, &c) == 3 ) { double2str(b, bstr); double2str(c, cstr); fprintf(stdout, " %4d & %s & %s & %6.2lf \\\\\n", a, bstr, cstr, 1.0E-6*c/b); } else { // the line contains something else: fprintf(stdout, "%s", line); } // read the next line from the input: fgets(line, MAXLINE, stdin); } fclose(stdout); return 0; } char* double2str(double d_, char* str_) { // converts the real number d_, to scientific notation in LaTeX format // e.g., 3.14E0 --> $3.14\cdot 10^{0} // stores the result in str_ (NOTE: it must be large enough) // the return value is str_ double exponent; double coefficient; // the exponent is the log_10 of the (absolut value of the) number: exponent = log10(fabs(d_)); // if the number is 0 (or -0) we do not use the scientific notation: // for the explanation of HUGE_VAL see: // http://www.cplusplus.com/reference/clibrary/cmath/log10/ if ( exponent == -HUGE_VAL ) { sprintf(str_, "$%2.0f$", d_); return str_; } // the exponent in the scientific notation should be integral: exponent = floor(exponent); // calculate the coefficient, using the exponent coefficient = d_ * pow(10.0, -exponent); // store the result: sprintf(str_, "$%5.2lf\\cdot 10^{%d}$", coefficient, (int)exponent); return str_; }