如何制作这样的对称直方图?

hc2pp10m  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(349)

我想编写一个javascript程序来显示对称直方图,如下图所示:

程序应要求用户输入要打印的条数和用于绘制条的字符。条形图中的字符数需要显示在每个条形图的右侧。
显示的示例是当我输入@作为字符,输入13作为数字时。
这是我的密码:

var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;

while (currentNum <= number) {
  text += "<br>" + symbolNum + " " + currentNum;
  symbolNum += symbol;
  currentNum++;
}

document.write(text + "<br>");

最后,我只能输出以下内容:

我想知道我能做些什么来扭转这个循环?

ggazkfy8

ggazkfy81#

两种不同的方法可以获得相同的结果。不是真的很干净,而是工作。

var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;

while (currentNum <= number) {
  textTOP += "<br>" + symbolNum + " " + currentNum;
  if (currentNum < number)
      textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
  symbolNum += symbol;
  currentNum++;
}

document.write(textTOP + textBOTTOM + "<br>");
var symbol = '@';
var number = 13;

var currentNum = 1;
let text = "";

while (currentNum <= number * 2) {

  if (currentNum <= number) {

    let num = currentNum;
    text += "<br>" + symbol.repeat(num) + " " + num;

  } else {

    let num = Math.abs(number * 2 - currentNum);
    text += "<br>" + symbol.repeat(num) + " " + num;

  }

  currentNum++;
}

document.write(text + "<br>");
mrwjdhj3

mrwjdhj32#

试试这个

function SymmetricHistogram(){

const size = 10;
let numberX = 0;
let numberY = 0;

for(let i = size; i>=-size; i--) {
  for(let j=size; j>=Math.abs(i); j--){
    process.stdout.write("@");
  }
  numberX <=size ? console.log(numberX++) : console.log(--numberY);
}

  }

  SymmetricHistogram();

或者试试下面的方法
https://onecompiler.com/javascript/3x58bqr3h

相关问题