定义比例因子以图形化三个量,其总和为常数

问题描述

我试图在标准输出中编写图形,程序返回“#”行,在另一个函数对其进行更改后,该行应加起来等于初始数量。我保证修改数字的功能不会出错。这是我的代码

struct mystruct {
    long long int s;
    long long int i;
    long long int r;
}

mystruct initial_;

void draw_row(mystruct P)
{
    long long int Ntotal = initial_.s + initial_.i;
    int scale = round(Ntotal / 10);
    std::string a(Ntotal / scale,'#');
    std::string b(round(P.s / scale),'#');
    std::string c(round(P.i / scale),'#');
    std::string d(round(P.r / scale),'#');
    std::cout << P.s << " " << P.i << " " << P.r << '\n';
    std::cout << scale << '\n';
    std::cout << a << '\n' << b << c << d << '\n';
}

这些是其某些输出的示例:

499 1 0
##########
#########

0 450 50
##########
##########

0 249 251
##########
#########

解决方法

您正在对行进行整数除法

int scale = round(Ntotal/10) ; 
std::string a(Ntotal/scale,'#') ;
std::string b(round(P.s/scale),'#') ;
std::string c(round(P.i/scale),'#') ;
std::string d(round(P.r/scale),'#') ;

,其余部分被截断,因此此处使用的round()无法正常工作。

您可以执行(A + B/2) / B来舍入两个正整数A / B的除法结果,因此行应为

int scale = (Ntotal+5)/10 ; 
std::string a(Ntotal/scale,'#') ;
std::string b((P.s+scale/2)/scale,'#') ;
std::string c((P.i+scale/2)/scale,'#') ;
std::string d((P.r+scale/2)/scale,'#') ;
,

我将绘制的第一列显示为最大可能值,即a = Ntotal = initial_.s + initial_.i >= P = P.s + P.i + P.r,所有内容除以scale

由于多个整数除法(P.s + P.i + P.rNtotal引入的截断错误,第二scale = round(Ntotal/10)列有时比第一b,c,d = round(P.(s,i,r)/scale)短。

您不能完全克服问题,但是可以通过扩大比例来改善表示,即减少scale参数,这会延长列的使用时间(它们最终将包含更多的{{1} }。