Thread: What is wrong with my code? using structs and fprintf

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    15

    What is wrong with my code? using structs and fprintf

    I am working on a function for my project that formats the output of complex(imaginary) numbers, but when I run it, its not being formatted as i thought it would be.
    the struct being used is:

    Code:
    typedef struct {
      double re;
      double im;
    } complex;
    And I am unable to change the type of re and im in the struct
    the function i have written for this so far is:

    Code:
    void output_complex(FILE *outf,complex z)
    {
       if(z.im == 0)
       {
          fprintf(outf,"%f", z.re);
       }
       if(z.re == 0)
       {
          if(z.im == 1)
          {
    	 fprintf(outf,"i"); 
          }
          fprintf(outf,"%fi", z.im);
       }
        if(z.im == 1)
       {
          fprintf(outf,"%f + i", z.re);
       }
       if(z.im < 0)
       {
          if(z.im == -1)
          {
    	 fprintf(outf,"%f - i", z.re);
          }
          z.im *= -1;  
          fprintf(outf,"%f - %fi", z.re, z.im);
       }
       fprintf(outf,"%f + %fi", z.re, z.im);
    }
    and there is this program that checks to see if the expected output is the same as the output of the function and this is what I got when I ran it for this function:
    Output Function Errors:
    expected: 1 + 2i
    actual: 1.000000 + 2.000000i
    expected: 3
    actual: 3.0000003.000000 + 0.000000i
    expected: 4i
    actual: 4.000000i0.000000 + 4.000000
    expected: i
    actual:
    expected: -2 + i
    actual: i1.000000i0.000000 + i0.0000
    expected: 4 - 2i
    actual: 0 + 1.000000i
    expected: 3 + 2i
    actual: -2.000000 + i-2.000000 + 1.0
    expected: 2 - i
    actual: 0000i

    what am I doing wrong?

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Moved to duplicate thread: What is wrong with my code? using structs and fprintf.

    Mods, feel free to close this one.
    Last edited by anduril462; 04-06-2011 at 05:54 PM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    21
    Also, you should check out string formatting characters, and how to set limits on them.Wikipedia's prinf page is a good place to start.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with printf in array of structs...
    By Huskar in forum C Programming
    Replies: 2
    Last Post: 03-29-2009, 10:13 PM

Tags for this Thread