例如,我想要此输出
Subtotal 20
Discount(10%) - 2 //negative sign always have 2 spaces out from '2'
我试图这样编码。
dis = subtotal*discount/100; //dis = 20*10/100
printf("Subtotal%13d\n",subtotal);
printf("Discount(%d%s)%4s-%3d\n",discount,"%"," ",dis);
但是如果没有折扣,我的输出将变成这样
数字向前移到左侧
Subtotal 20
Discount(0%) - 0
此外,如果我的小计和折扣很大。
负号和数字连在一起
Subtotal 1000
Discount(50%) -500
如何对此编码,直到我的数字在折扣(0%-100%)之间始终不移到左侧或右侧,并且始终在负号和数字(dis)之间留2个空格?
答案 0 :(得分:1)
据我所知,using System.Collections.Immutable;
using System.Windows;
using System.Windows.Data;
using Telerik.Windows.Controls.ChartView;
namespace CustomYAxis
{
public class ChartYAxisAnnotation : CartesianCustomAnnotation
{
private readonly CustomYAxisView _annotationContent;
public ChartYAxisAnnotation()
{
Content = _annotationContent = new CustomYAxisView();
// These bindings aren't working
var widthBinding = new Binding(nameof(WidthProperty))
{
Source = this,
};
var heightBinding = new Binding(nameof(HeightProperty))
{
Source = this
};
_annotationContent.SetBinding(WidthProperty, widthBinding);
_annotationContent.SetBinding(HeightProperty, heightBinding);
}
}
}
和数字之间没有标记来增加空格,但是一种解决方案可能是添加一个额外的字符串缓冲区以写出所需的格式:
-
答案 1 :(得分:0)
您非常接近。问题是,如果仅指定数字的宽度,默认情况下将右对齐,这就是为什么要在不同位置打印不同大小的数字的原因。
类似这样的东西应该更接近您想要的东西:
sudo jack-diagnose
答案 2 :(得分:0)
如果您只想在-
和第一位数字之间保留固定数量的空格,则只需输出以下空格:"Discount(%2d%%) - %d\n"
但是,请注意,由于数字的宽度取决于其大小,因此将很难与上面的线对齐。为了与上面的行保持一致,您要么需要为折扣号设置一个固定的字段宽度(并保留额外的空格,否则将产生大量数字时的失败),或者您需要计算第二个宽度行第一行,并相应地填充第一行。可以通过使用asprintf()
将第二行写入新分配的字符串,然后获取该字符串的长度,并相应地格式化第一行来实现后者。最后一步是逐字输出第二行的字符串。
答案 3 :(得分:0)
您可以使用:
printf
,告诉您如何打印字符log10
函数,可用于了解整数中的字符数:代码如下:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* get number of character in a number (when printed)*/
int int_print_size(int number)
{
if (number < 1)
return 1;
else
return 1+log10(number);
}
void print(int subtotal, int discount)
{
char spaces[] = " ";
int dis = subtotal*discount/100; //dis = 20*10/100
int ref, len[2];
/* take size of first line as reference */
ref = printf("Subtotal%13d\n",subtotal);
/* take the size of first part */
len[0] = printf("Discount(%d%%)",discount);
/* compute the printed size of `dis` */
len[1] = int_print_size(dis);
/* pad with characters from `spaces` array */
printf("%.*s- %d\n\n", ref-4-len[0]-len[1], spaces, dis);
}
int main(int argc, char *argv[]){
/* tests case */
print(20, 0);
print(20, 10);
print(100, 9);
print(100, 10);
print(100, 11);
print(1000, 50);
print(100000, 99);
return 0;
}
结果:
Subtotal 20
Discount(0%) - 0
Subtotal 20
Discount(10%) - 2
Subtotal 100
Discount(9%) - 9
Subtotal 100
Discount(10%) - 10
Subtotal 100
Discount(11%) - 11
Subtotal 1000
Discount(50%) - 500
Subtotal 100000
Discount(99%)- 99000
答案 4 :(得分:0)
如果您想坚持使用printf
系列,可以执行以下操作:
void print(int subtotal, int discount, int dis) {
char buf[255] = { 0 };
sprintf(buf, "Discount(%d%%)", discount);
printf("%-21s %4d\n", "Subtotal", subtotal);
printf("%-21s- %4d\n", buf, dis);
}
不幸的是,它使用了中间缓冲区。如果您想避免这种情况,我怀疑您最好针对这种情况滚动自己的格式代码。