如何基于余数、百分比或浮点值进行循环?

How can I loop based on remainders, percentages, or floating point values?

提问人:Charlimagne 提问时间:10/25/2023 最后编辑:John KugelmanCharlimagne 更新时间:10/26/2023 访问量:81

问:

我的作业要求我采用不同整数形式的数据集,并通过一种方法运行它们,该方法将打印适当数量的字符以创建水平条形图。 该图需要使用由块元素 (, , ) 组成的字符串。块以 8 为基数,因此应以整数形式输入 8,应打印 16。██

我想出了一种方法,可以为可被 8 整除的输入打印正确数量的块,但我不确定如何处理来自不均匀除法的余数或十进制值,例如,如果 (9 / 8) = 1.125,我如何使用 0.125?

这就是我目前所拥有的。它为 8 的倍数打印适当数量的字符。

public static String getHorizontal(int value) {
   String bar = "";
   double realMath = (double) value / 8; // (1/8) = (0.125) (8/8) = 1
   int rmConversion;

   while (realMath % 1 == 0) {
       rmConversion = (int) realMath;
       for (int i = 0; i < rmConversion; i++) {
           bar += "█";
       }
       return bar;
   }

   // TODO: replace this with code that actually generates the bar graph!

   return bar;
}

如何运行类似的循环,但使用余数或小数点值?

Java 循环 浮点 分数

评论

0赞 user2260040 10/25/2023
您确定需要绘制十进制值吗?
0赞 Charlimagne 10/25/2023
@user2260040我不必以这种方式处理它,但我不确定还能如何处理它。但是如果 int 输入是 9,那么我必须同时打印 1/8 块元素和 8/8 块元素。
0赞 Bohemian 10/25/2023
不确定,但请尝试代替while (realMath % 1 < 0.0000001)while (realMath % 1 == 0)
0赞 Old Dog Programmer 10/25/2023
检查代码中的循环。因为它总是 ,循环要么迭代零次,要么迭代一次。因此,它等价于 .这是你想要的吗?whilereturnwhileif

答:

1赞 Old Dog Programmer 10/25/2023 #1

这是一种方法。请注意,此答案中的所有计算都是以整数算术完成的。不使用浮点。

  • 通过除以 8 来计算所需的完整块数。
  • 将该数字加 1 可为部分块保留空间。
  • 创建一个在上一步中确定的长度数组,其中填充了完整的块字符。
  • 使用运算符计算余数,这将给出部分块的大小。%
  • 将填充数组中的最后一个字符替换为空格或部分块,由余数计算结果确定。
  • 如果确实需要显式循环,请将调用替换为循环。Arrays.fill
public static String bar (int value) {
    final char FULL_BLOCK = '█';
    char [] partBlock = {' ','▏','▎','▍','▌','▋','▊','▉' };
    char [] theBar = new char [value / 8 + 1];
    Arrays.fill (theBar, FULL_BLOCK);
    theBar [theBar.length - 1] = partBlock [value % 8];
    return new String (theBar);
}
   
public static void main(String[] args) {
    System.out.println ("Growing Bar:");
    for (int i = 0; i <= 24; ++i) {
        System.out.println (bar (i));
    }
}

测试:

Growing Bar:
 
▏
▎
▍
▌
▋
▊
▉
█ 
█▏
█▎
█▍
█▌
█▋
█▊
█▉
██ 
██▏
██▎
██▍
██▌
██▋
██▊
██▉
███

整个块和部分块之间的高度不均匀似乎是 Stack Overflow 使用的字体的结果。我在其他任何地方(例如我的 IDE、电子邮件或文本编辑器)的测试结果中都看不到这种差异。

使用数组的另一种方法是利用部分块是 Unicode 中的连续字符这一事实:partBlock

int r = value % 8;
theBar[theBar.length - 1] = r == 0 ? SPACE : (char) ('\u2590' - r);

当然,空格字符不适合该模式,因此必须为此进行检查。

0赞 Reilas 10/25/2023 #2

除以 8,然后将值四舍五入到最接近的 0.125

x = Math.round(x / 8 / .125) * .125

然后,确定要使用的八分之一块

x -= Math.floor(x);
char c = (char) (0x258f - (x / .125));

下面是一个示例。

String getHorizontal(double x) {
    x = Math.round(x / 8 / .125) * .125;
    String s = "\u2588".repeat((int) Math.floor(x));
    x -= Math.floor(x);
    return s + (char) (0x258f - (x / .125));
}

下面是一个输出。
您需要不同的字体,它适用于 Source Code Pro

1.125 ▎
11.25 █▌
56.25 ███████▏
112.5 ██████████████▎

评论

0赞 Old Dog Programmer 10/25/2023
O/P 取 a ,将其转换为 a,然后除以 8。我看不出“将值四舍五入到最接近的 0.125”有用。intdouble
0赞 Reilas 10/26/2023
@OldDogProgrammer,很酷。