int main() {
int i, repeatName; // ints
char firstName[50]; // array to store users name
// get first name from user
printf("Please enter your first name: ");
scanf("%s", firstName);
// get amount of times user would like to repeat name
printf("How many times would you like to repeat your name?: ");
scanf("%i", &repeatName);
// tell user name has to be repeated at last one
if (repeatName < 1) {
printf("The name has to be repeated at least one (1) time. Try again: ");
scanf("%i", &repeatName);
}
// for loop to repeat name 'x' number of times
for (i = 0; i < repeatName; i++) {
printf("%s \n", firstName);
}
}
例如:如果用户想要显示他们的名字3次,则会说:
Your name
Your name
Your name
我怎么能说:
Line 1 Your name
Line 2 Your name
Line 3 Your name
答案 0 :(得分:1)
使用循环中的i
变量作为行号
for (i = 0; i < repeatName; ++i)
printf("Line %d %s\n", i + 1, firstName);
请务必添加1,因为循环索引从0开始。您希望第一行说“Line 1”,而不是“Line 0”,依此类推。
编辑:当行号超过一位时,输出效果不佳。要解决这个问题,你可以写
for (i = 0; i < repeatName; ++i)
printf("Line %-6d%s\n", i + 1, firstName);
这使得行号至少占用6个字符,并使数字左对齐:
Line 1 this is my string
Line 2 this is my string
Line 3 this is my string
Line 4 this is my string
Line 5 this is my string
Line 6 this is my string
Line 7 this is my string
Line 8 this is my string
Line 9 this is my string
Line 10 this is my string
答案 1 :(得分:1)
据我所知,没有办法自动执行此操作。但是你可以让for循环中的i变量也充当行计数器,因为每次迭代都会打印一行:
// for loop to repeat name 'x' number of times
for (i = 0; i < repeatName; i++) {
printf("Line %d %s \n", i + 1 /* Lines are not 0 based */ , firstName);
}
答案 2 :(得分:0)
只需在打印时添加循环索引:
for (i = 0; i < repeatName; i++) {
printf("Line %d %s \n", i+1, firstName);
}
答案 3 :(得分:0)
尝试此代码
#include <stdio.h>
int main()
{
int i, repeatName; // ints
char firstName[50]; // array to store users name
// get first name from user
printf("Please enter your first name: ");
scanf("%s", firstName);
// get amount of times user would like to repeat name
printf("How many times would you like to repeat your name?: ");
scanf("%i", &repeatName);
// tell user name has to be repeated at last one
if (repeatName < 1) {
printf("The name has to be repeated at least one (1) time. Try again: ");
scanf("%i", &repeatName);
}
// for loop to repeat name 'x' number of times
for (i = 1; i <= repeatName; i++) {
printf("Line %d Your name %s \n",i,firstName);
}
}