如何解决定义比例因子以图形化三个量,其总和为常数
我试图在标准输出中编写图形,程序返回“#”行,在另一个函数对其进行更改后,该行应加起来等于初始数量。我保证修改数字的功能不会出错。这是我的代码:
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.r
和Ntotal
引入的截断错误,第二scale = round(Ntotal/10)
列有时比第一b,c,d = round(P.(s,i,r)/scale)
短。
您不能完全克服问题,但是可以通过扩大比例来改善表示,即减少scale
参数,这会延长列的使用时间(它们最终将包含更多的{{1} }。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。