我练习c并且我在使用此代码时遇到了一些问题: 我想制作一个电影院门票计划。 这些节目正在加速一个特定的数字,并寻求第一个免费座位,如果没有,它会打印按摩。 座椅必须相互连接并且在同一排。 座椅的索引需要打印以及标记为采取.. Im标记为1,0标记为未标记。 我需要你的帮助,每次都如何保存索引。
#include <stdio.h>
#include <string.h>
main()
{
int i, j;
int Freeseats = 0;
int arr[10][20]= {{0}};
for(i=0; i<10; i++)
{
for(j=0; j<20; j++)
{
printf("%d", arr[i][j]);
}
printf("\n");
}
while(1)
{
int num, n=0;
scanf("%d",&num);
for(i=0; i<10; i++)
{
for(j=0; j<20; j++)
{
if(arr[i][j] == 0 && Freeseats < num)
{
Freeseats++;
}
else{
Freeseats = 0;
}
if(Freeseats == num)
{
}
}
}
}
}
答案 0 :(得分:0)
我认为你的做法是错误的。您不需要保存任何索引。
你的任务是找到一个连续N个座位的行。所以你需要一个额外的循环来计算连续的免费座位数。
类似的东西:
#include <stdio.h>
#include <string.h>
#define SEATS_PER_ROW 20
#define ROWS 10
main()
{
int i, j, k, max;
int arr[ROWS][SEATS_PER_ROW]= {{0}};
for(i=0; i<10; i++)
{
for(j=0; j<20; j++)
{
printf("%d", arr[i][j]);
}
printf("\n");
}
while(1)
{
printf("Please enter the number of seats needed\n");
int num, n=0;
if (1 != scanf("%d",&num))
{
printf("Illegal input - stop program\n");
break;
}
printf("Searching for %d seats\n", num);
if (num > SEATS_PER_ROW)
{
printf("We don't have that many seats in a single row\n");
continue;
}
int found = 0;
for (i=0; i<10 && found != 1; i++)
{
found = 0;
for (j=0; j<(20-num+1) && found != 1; j++)
{
found = 0;
// Check for num consecutive free seats starting at i, j
for (k=0; k<num; k++)
{
if(arr[i][j+k] != 0)
{
// Can't sit here
found = -1;
break;
}
}
if (found == 0)
{
// We found a place - starting at i, j
// Mark them as used
found = 1;
printf("Seats assinged in row %d : seat %d to %d\n", i, j, j+num-1);
for(k=0; k<num; k++)
{
arr[i][j+k] = 1;
}
// Debug print
//for(i=0; i<10; i++)
//{
// for(j=0; j<20; j++)
// {
// printf("%d", arr[i][j]);
// }
// printf("\n");
//}
}
}
}
if (found != 1)
{
printf("So many seats are not available\n");
}
}
return 0;
}
输入:
10
15
2
6
20
3
21
9
输出结果为:
Please enter the number of seats needed
Searching for 10 seats
Seats assinged in row 0 : seat 0 to 9
Please enter the number of seats needed
Searching for 15 seats
Seats assinged in row 1 : seat 0 to 14
Please enter the number of seats needed
Searching for 2 seats
Seats assinged in row 0 : seat 10 to 11
Please enter the number of seats needed
Searching for 6 seats
Seats assinged in row 0 : seat 12 to 17
Please enter the number of seats needed
Searching for 20 seats
Seats assinged in row 2 : seat 0 to 19
Please enter the number of seats needed
Searching for 3 seats
Seats assinged in row 1 : seat 15 to 17
Please enter the number of seats needed
Searching for 21 seats
We don't have that many seats in a single row
Please enter the number of seats needed
Searching for 9 seats
Seats assinged in row 3 : seat 0 to 8
Please enter the number of seats needed
Searching for 15 seats
Seats assinged in row 4 : seat 0 to 14
上查看