Thread: Printf Problem

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    4
    Rep Power
    0

    Printf Problem


    The program seems to print out the s and c values for every integer up until n, including n, but I only want to print out the values of s and c for n. Any help with this problem?
    Code:
    #include <stdio.h>
    #include <math.h>
    
    int main()
    {
        double n,s,c;
        while(scanf("%d", &n)&&n)
        {
                                 s=(2*pow(n,3)+3*pow(n,2)+n)/6;
                                 c=pow(n*n+n,2)/4;
                                 printf("%d %d\n", s,c)
        }
        return 0;
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,253
    Rep Power
    2222
    %d is to output a decimal integer. s and c are not integers, but rather double (double precision floating-point). Their internal formats are completely different. You are telling the compiler to misrepresent floating-point values as if they were integer, the results of which is incomprehensible garbage.

    %f and %g are used for floating point. You should also consider using them in the scanf, since you are now telling scanf to store an integer value in the memory location of a double, thus immediately turning the input value into instant garbage as the program will thereafter misinterpret that integer as a floating-point value, a really messed up one. Garbage in, raised to the garbage power, rehashed as new garbage on the way out ... you've got a real mess on your hands there.

    So input and output those floating-point values as floating-point. After you've gotten that corrected, then come back with more questions.

IMN logo majestic logo threadwatch logo seochat tools logo