英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论