-1

I have a problem. I need to insert a specific char (number sign) into my output value. I am not allowed to use if statement and "? :" statement. My output needs to look like this:

9999.999(+/-)i9999.999

Where character "i" needs to go right after the 2nd number sign. Here is my code so far:

void show(struct z z) {
    printf("%.3fi%.3f", z.re, z.im);
}

3 Answers3

2

without if or ternary

void show(struct z z) {
    printf("%.3f%ci%.3f", z.re, "+-"[z.im<0], fabs(z.im));
}
pm100
  • 48,078
  • 23
  • 82
  • 145
1

Use a conditional (aka "ternary") expression to print + or - depending on the sign of the imaginary part. Then print the absolute value of the imaginary part.

void show(struct z z) {
    printf("%.3f%ci%.3f", z.re, (z.im >= 0 ? '+' : '-'), fabs(z.im));
}

If you can't use a ternary, either, you can format the number with a forced sign into a string, then swap the i and sign in the result.

void show(struct z z) {
    char result[100];
    sprintf(result, "%.3fi%+.3f", z.re, z.im);
    int iloc = strchr(result, 'i');
    result[iloc] = result[iloc+1];
    result[iloc+1] = 'i';
    printf("%s", result);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

To properly handle -0.0 and NAN, extract the sign with signbit() and use the string trick as in @pm100.

The signbit macro determines whether the sign of its argument value is negative. (footnote)
The signbit macro returns a nonzero value if and only if the sign of its argument value is negative.
The signbit macro reports the sign of all values, including infinities, zeros, and NaNs.

#include <math.h>

// 9999.999(+/-)i9999.999
printf("%.3f%ci%.3f", z.re, "-+"[!signbit(z.im)], fabs(z.im));
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256