我试图在C中制作一个程序,为用户提供一个预订学习室的菜单
1.预约房间
2.休息室
3.显示可用房间
退出
共有10间客房。我不确定如何在数组中使用更改值,其中0 ==房间打开,1 = =房间关闭。
#include <stdio.h>
void print_arr(int room[], int elements);
int search_arr(int room[], int elements, int open);
int main(void)
{
int room[10] = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 }; // array for 10 rooms
int result, open;
print_arr(room, 10);
open = 0;
result = search_arr(room, 10, open);
if (result == -1)
printf("There are no open rooms. \n");
else
printf("There are %d vacant Rooms. ", result);
return 0;
}
void print_arr(int room[], int elements)
{
int i;
printf("Rooms: ");
for (i = 0; i < elements; i++)
{
printf("%d ", room[i]);
}
printf("\n");
}
int search_arr(int room[], int elements, int open)
{
int i;
for (i = 0; i < elements; i++)
{
if (room[i] == open)
printf("Vacant Room: %d \n", room[i]);
return(open); //found open rooms
}
return(-1); //no open rooms found
}
答案 0 :(得分:0)
您的搜索例程在每种情况下都返回0(这是打开的值),并且在找到的第一个打开的房间中执行此操作。要计算开放的房间,在看到每个元素之前都不能返回,每当你看到一个“开放”的房间时你就必须增加一个计数器。
int search_arr(int room[], int elements, int open)
{
int i, openrooms=0;
for (i = 0; i < elements; i++)
if (room[i] == open)
openrooms++;
return openrooms; // returns 0 when none found...
}
答案 1 :(得分:0)
您必须计算阵列中免费(开放)房间的数量,例如:
int search_arr(int room[], int elements, int open)
{
int free = 0;
int i;
for (i = 0; i < elements; i++)
{
if (room[i] == open) {
printf("Vacant Room number: %d \n", i);
free++;
}
}
return(free); // return number of vacant rooms; 0 if no rooms are free ;-)
}
答案 2 :(得分:0)
search_arr
函数中使用的逻辑是错误的。它应该是 -
int search_arr(int room[], int elements, int open)
{
int i;
for (i = 0; i < elements; i++)
{
if (room[i] == 0)
{printf("Vacant Room No: %d \n", i);
open++; //found open rooms
}} if(open)
return(open);
return(-1); //no open rooms found
}