打印Python中的三角形数,同时还要打印输入之前的数字。

huangapple go评论61阅读模式
英文:

How to print Triangular numbers using For Loop while also printing numbers prior to input in Python

问题

以下是翻译好的部分:

j = int(input('你想要打印多少行三角形?:'))
num1 = 1

for i in range(0, j):
  num1 = ((j**2)+j) / 2
  print(num1)

你的代码中可能有一个问题,导致它只打印出一个数字。你可能需要在循环中使用不同的变量来计算不同行的三角数。

英文:

So one of my school project has me wanting to print out triangular numbers, where they ask for a prompt (input) of how many rows of dots i want to print out and it would print out the triangular number, while also printing out the triangular numbers that were less than that prompt

I tried using a For Loop and I did successfully manage to get the system to print out the amount of numbers displayed, but for some reason it just only printed out whats needed in the prompt

What is should be:

how many lines you want on your triangle?: 3
1.0
3.0
6.0

How it's being printed out:

how many lines you want on your triangle?: 3
15.0
15.0
15.0

The code:

j = int(input('how many lines you want on your triangle??????: '))
num1 = 1

for i in range(0, j):
  num1 =((j**2)+j)/(2) 
  print(num1)

I'm aware I got the formula wrong, but i still want to know why it's only printing one number

答案1

得分: 2

你将num1计算为j的函数,但在循环中使用i

英文:

You calculate num1 as a function of j, but loop over i.

答案2

得分: 0

你差一点就成功了,但忘记了使用范围内的各种值。

j = int(input('你想要三角形有多少行?:'))
    
for i in range(1, j+1):
    print((i*i+i)//2)

控制台:

你想要三角形有多少行?:5
1
3
6
10
15
英文:

You almost had it but forgot to use the various values in the range.

j = int(input('how many lines do you want on your triangle?: '))

for i in range(1, j+1):
    print((i*i+i)//2)

Console:

how many lines do you want on your triangle?: 5
1
3
6
10
15

huangapple
  • 本文由 发表于 2023年5月11日 01:48:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定