简体   繁体   中英

How to print a positive number as a negative number via printf

While reading about printf(),I found that it can print numbers as positive or negative as desired by the user by following code(for -).But the code doesnt work and the output is a positive value.Please mention where the error is.Thanks

#include<stdio.h>
int main()
{
  printf (" %-d\n", 1977);
  return 0;
}

From your comments it looks like you misread this page . The - and + specifiers do two completely different things, and neither does what you think '-' should do.

As others have noted, - does left justification. The + specifier prints positive numbers with a leading plus sign (and negative numbers still get a leading minus sign):

printf("%d %d %+d %+d\n", -10, 10, -10, 10);

outputs:

-10 10 -10 +10

%-d Will left adjust the integer field, it won't flip the sign. Do this instead:

printf (" %d\n", -1977);

Here's the full extract from print(3) under The flag characters :

-      The  converted  value is to be left adjusted on the field bound‐
              ary.  (The default is right justification.)  Except for  n  con‐
              versions,  the  converted  value  is  padded  on  the right with
              blanks, rather than on the left with blanks or zeros.  A - over‐
              rides a 0 if both are given.

Update0

I see your true question now: To prepend output with the appropriate sign, use the + flag character to explictly show the sign. Again here is the extract:

+      A sign (+ or -) should always be placed before a number produced
              by a signed conversion.  By default a sign is used only for neg‐
              ative numbers.  A + overrides a space if both are used.

And use it like this (The command line printf is mostly identical):

matt@stanley:~/cpfs$ printf "%+d\n" 3
+3
matt@stanley:~/cpfs$ printf "%+d\n" -3
-3
matt@stanley:~/cpfs$ printf "%+u\n" -3
18446744073709551613

Be aware that explicitly requesting the sign won't imply treatment of the corresponding integer as signed as in the %u example above.

printf (" -%d\\n", 1977); will output -1997 (bad way to do it), if you would like negative numbers to become positive, do printf (" %d\\n", -1 * 1977); (good way to do it)

read the reference for an idea of how format specifiers work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM