[英]Triangle number program in C language?
I want to make a simple triangle number program 1, 3, 6, 10,...
that is no more than 100
,I already made it.我想做一个简单的三角形数程序
1, 3, 6, 10,...
不超过100
,我已经做到了。 but there is little problem但问题不大
lets take a look at my code:让我们看看我的代码:
#include <stdio.h>
int main (void){
int j=1 , k=1 , i=100 , status;
while (k <= i){
j = j + 1;
k = k + j;
while ( k < 100){
printf (" %d\n",k);
status = 1;
break;
}
}
if (status == 1){
printf ("DONE!");
}
}
output: output:
3
6
10
15
21
28
36
45
55
66
78
91
DONE !
From here, I have some problem:从这里,我有一些问题:
While
Command,because when I only use one While
the output will be bigger than 100
it will be 105
.While
命令,因为当我只使用一个While
output 将大于100
它将是105
。 So there is a way to simplify this by using one while
command?while
命令来简化这一点吗?1
, i want to make the program outputting like this: 1
开头,我想让程序输出如下:1
3
6
10
15
21
28
36
45
55
66
78
91
DONE !
but in the end, The output always start with number 3
?但最后,output 总是以数字
3
开头?
Your approach is far too complicated.你的方法太复杂了。 You only need one loop, a running sum and a variable to hold the next value to be added to sum.
您只需要一个循环、一个运行总和和一个变量来保存要添加到总和的下一个值。
Start the running sum at zero, then add 1 and print the sum, then add 2 and print the sum, then add 3 and print the sum... keep doing that until the sum gets above 100.从零开始运行总和,然后加 1 并打印总和,然后加 2 并打印总和,然后加 3 并打印总和......继续这样做,直到总和超过 100。
Like:喜欢:
#include <stdio.h>
int main(void) {
int sum = 0;
int nextToAdd= 1;
while(1)
{
sum += nextToAdd;
++nextToAdd;
if (sum > 100) break;
printf("%d\n", sum);
}
return 0;
}
or if you prefer do-while或者如果你更喜欢 do-while
#include <stdio.h>
int main(void) {
int sum = 1;
int nextToAdd = 1;
do
{
printf("%d\n", sum);
++nextToAdd;
sum += nextToAdd;
} while(sum <= 100);
return 0;
}
or if you prefer a for-loop或者如果您更喜欢 for 循环
#include <stdio.h>
int main(void) {
int sum = 1;
for (int nextToAdd = 2; sum <= 100; ++nextToAdd)
{
printf("%d\n", sum);
sum += nextToAdd;
}
return 0;
}
when you use only one while, when k=91
so k<=100
and the condition of while
is true and so you will enter while and k
will become 105
and you will print it.当你只使用一个 while 时,当
k=91
所以k<=100
并且while
的条件为真,所以你将输入 while, k
将变为105
,你将打印它。 so you need one if
before printf
to check if(k<100)
.所以你需要一个
if
在printf
之前检查if(k<100)
。
also here if you initialized k=0
and replace k+=j
and with j++
you will also print 1
.同样在这里,如果您初始化
k=0
并替换k+=j
并使用j++
您还将打印1
。
look:看:
int main()
{
int k = 1, j = 2, i = 100;
while (k <= i) {
printf("%d\n", k);
k += j;
j++;
}
printf("DONE!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.