给出numRows和numCols,打印剧院中所有座位的列表。行编号,列字母,如1A或3E中所示。在每个座位后打印一个空格,包括在最后一个之后。例如:numRows = 2和numCols = 3打印: 1A 1B 1C 2A 2B 2C
我有什么:
#include <stdio.h>
int main(void) {
int numRows = 2;
int numCols = 3;
int rows = 0;
char cols = 'A';
char var = 'A';
for (rows = 1; rows<=numRows; ++rows){
for (cols = 0; cols<numCols; cols++){
printf("%d", rows);
printf("%c ", var);
++var;
}
}
printf("\n");
return 0;
}
打印:
1A 1B 1C 2D 2E 2F
但我想要打印
1A 1B 1C 2A 2B 2C
如何让它重复A B C?
答案 0 :(得分:2)
每次进入内部循环之前,您必须重置var
的值。
#include <stdio.h>
int main(void) {
int numRows = 2;
int numCols = 3;
int rows = 0;
char cols = 'A';
char var;
for (rows = 1; rows<=numRows; ++rows){
var = 'A'; /* This is the change you are looking for. */
for (cols = 0; cols<numCols; cols++){
printf("%d", rows);
printf("%c ", var);
++var;
}
}
printf("\n");
return 0;
}
实现相同的更简单方法 -
int numRows = 2;
int numCols = 3;
int rows;
char cols;
for (rows = 1; rows <= numRows; ++rows){
for (cols = 'A'; cols < ('A' + numCols); cols++){
printf("%d", rows);
printf("%c ", cols);
}
}
答案 1 :(得分:1)
将for循环更改为:
for (rows = 1; rows<=numRows; ++rows){
for (cols = 0; cols<numCols; cols++){
printf("%d", rows);
printf("%c ", var + cols % 3);
}
}
您不想更新var
的值,因为它引用A
。
这是一个更好的版本:
#include <stdio.h>
int main(void) {
int numRows = 2;
int numCols = 5;
for (int row = 1; row <= numRows; row++){
for (int col = 0; col < numCols; col++){
printf("%d%c ", row, 'A' + col);
}
}
printf("\n");
return 0;
}
答案 2 :(得分:-3)
for(;;)
{
char var='A';
for(;;)
{
}
}
这样做!!