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

When reading about printf (), I found that it can print numbers as positive or negative at the request of the user, using the following code (for -). But the code does not work, and the result is positive. error. thank

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

From your comments, it seems you are reading this page incorrectly . Specifiers -and +perform two completely different things, and not what you think you should not do.

, - . + "" ( - "" ):

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

:

-10 10 -10 +10

+7

%-d , . :

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

print(3) :

       -      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

: , +, . :

       +      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.

( printf ):

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

, , %u.

+4

printf (" -%d\n", 1977);outputs -1997(a bad way to do this), if you want negative numbers to become positive do printf (" %d\n", -1 * 1977);(a good way to do this)

read the reference for an idea of ​​how format specifiers work

+3
source

Source: https://habr.com/ru/post/1766230/


All Articles