printf / sprintf问题,在数字上删除符号。

时间:2022-05-18 19:24:40

I have a number that may be negative or positive and I want it to pop out of sprintf() without the negative or positive sign. How would I do it?

我有一个数字,可能是负的,也可能是正的,我想让它从sprintf()中跳出,而不带正负号。我该怎么做呢?

I tried %d % d %- d %+ d % -d % +d and none of them work.

我尝试了%d %d %- d %+ d %+ d %+ d,没有一个是有效的。

I tried gcc 4.8.2 and g++ 4.8.2 and it does not work. Is this a bug in gcc?

我尝试了gcc 4.8.2和g++ 4.8.2,但它不起作用。这是gcc中的一个bug吗?

1 个解决方案

#1


3  

There is no format string that applies a absolute value functionality.

没有应用绝对值功能的格式字符串。

Here is what you have to do:

以下是你必须做的:

#include <stdio.h>
#include <math.h>

void main()
{
  int num = -6000;
  printf("%d\n", abs(num));
}
  • %d will render 34 as 34 and -34 as -34.
  • %d表示34 34和-34 = -34。
  • % d will render 34 as (space) + 34 and -34 as -34.
  • % d将显示34 as(空格)+ 34和-34 as -34。
  • %+d will render 34 as +34 and -34 as -34.
  • %+d将显示34 as +34和-34 as -34。
  • "%5d will render 34 as (three spaces) + 34 and -34 as (two spaces) + -34. They both will use the field size 5.
  • “%5d将呈现34(三个空格)+ 34和-34(两个空格)+ -34。它们都将使用字段5。
  • "%-5d will render 34 as 34 + (three spaces) and -34 as -34 + (two spaces). They both will use the field size 5, but left justified because of -.
  • “%-5d将呈现34 + 34 +(3个空格)和-34 + 34 +(两个空格)。他们都将使用5号字段,但由于- - -而左对齐。

#1


3  

There is no format string that applies a absolute value functionality.

没有应用绝对值功能的格式字符串。

Here is what you have to do:

以下是你必须做的:

#include <stdio.h>
#include <math.h>

void main()
{
  int num = -6000;
  printf("%d\n", abs(num));
}
  • %d will render 34 as 34 and -34 as -34.
  • %d表示34 34和-34 = -34。
  • % d will render 34 as (space) + 34 and -34 as -34.
  • % d将显示34 as(空格)+ 34和-34 as -34。
  • %+d will render 34 as +34 and -34 as -34.
  • %+d将显示34 as +34和-34 as -34。
  • "%5d will render 34 as (three spaces) + 34 and -34 as (two spaces) + -34. They both will use the field size 5.
  • “%5d将呈现34(三个空格)+ 34和-34(两个空格)+ -34。它们都将使用字段5。
  • "%-5d will render 34 as 34 + (three spaces) and -34 as -34 + (two spaces). They both will use the field size 5, but left justified because of -.
  • “%-5d将呈现34 + 34 +(3个空格)和-34 + 34 +(两个空格)。他们都将使用5号字段,但由于- - -而左对齐。