对于我的编程作业,我必须创建3个程序,根据用户的输入在c中打印出基于星号的三角形。 3个程序之间的差异将是一个将用于循环,另一个将使用while循环,最后一个将使用goto。我有for循环程序以及goto程序,但是对于while循环程序我不知道如何将它合并到我的程序中。这是我带有for循环的程序,第二个程序是我在while循环版本中的尝试。
#include <stdio.h>
int main() {
int lines, a, b;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
/*create triangle based on inputed value */
for(a = 1; a <= lines; a++) {
for(b=1; b<= a; b++) {
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
Progam#2:
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
a++;
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
} while(1);
system("pause");
}
答案 0 :(得分:0)
在第二次b=1
循环
while
while(a <= lines) {
a++;
b=1; //you want to start b from 1 for each inner loop
while (b <= a) {
b++;
printf("*");
}
printf("\n");
}
答案 1 :(得分:0)
可以如下更改program2。以下代码结果相当于program1。
#include <stdio.h>
int main() {
int lines, a = 1, b = 1;
//prompt user to input integer
do{
printf("Input a value from 1 to 15: ");
scanf("%d", &lines);
//Check if inputed value is valid
if(lines < 1 || lines > 15) {
printf("Error: Please Enter a Valid number!!!\n");
continue;
}
while(a <= lines) {
//a++;
while (b <= a) {
b++;
printf("*");
}
b =1;
a++1;
printf("\n");
}
} while(1);
system("pause");
}`
答案 2 :(得分:0)
以下是转换for
循环的方法,如下所示
for (stat1; stat2; stat3) {
stat4;
}
到while
循环
stat1;
while (stat2) {
stat4;
stat3;
}
所以这是你想要的while
循环:
a = 1;
while(a <= lines) {
b = 1;
while (b <= a) {
printf("*");
b++;
}
printf("\n");
a++;
}