我正在编写一个程序,要求用户输入两个数字M和N.然后程序创建一个二维数组[M] [N]。
需要使用其他四个功能,包括:
我的代码存在的问题是,当我运行它并输入两个值时,程序会无限次地打印默认情况“输入1或0”。有人可以帮助我吗?
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
bool LinearSearch(int[][N], int);
void PopulateRandom(int[][N]);
void PrintArray2D(int[][N]);
void LeftShift(int[][N]);
// Prints elements of array in a M x N table
void PrintArray2D(int array[][N]) {
int i, j;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
printf("%d", array[i][j]);
}
printf("\n");
}
}
// Assigns elements of the array "array" random values
void PopulateRandom(int array[][N]) {
int i, j, x;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
bool found = 1;
while (found == 1) {
x = rand() % M * N - 1;
found = LinearSearch(array, x);
}
array[i][j] = x;
}
}
}
// functino performs a linear search to see if there are any repeated values
// in the array.
bool LinearSearch(int array[][N], int num) {
bool p_flag = 0;
int i, j;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
if (array[i][j] == num) {
p_flag = 1;
}
}
}
return p_flag;
}
void LeftShift(int array[][N]) {
int i;
int j;
for (i = 0; i < M; i++) {
for (j = 0; j < N; j++) {
if (j == N - 1) {
if (i == M - 1) {
array[i][j] = array[0][0];
} else {
array[i][j] = array[i + 1][0];
}
} else {
array[i][j] = array[i][j + 1];
}
}
}
}
int main(void) {
int option;
printf("If you would like to search ann array, enter 1 \n: ");
printf("If you would like to exit, enter 0 \n: ");
scanf("%d", &option);
while (option != 0) {
switch (option) {
case 1: {
printf("Enter two numbers M and N: ");
scanf("%d %d", &M, &N);
int array[M][N];
PopulateRandom(array);
PrintArray2D(array);
LeftShift(array);
PrintArray2D(array);
break;
}
case 0:
break;
default:
printf("Enter 1 or 0");
}
}
}
答案 0 :(得分:2)
试试这个:
int main(void) {
int option = 1;
while (option != 0) {
printf("If you would like to search ann array, enter 1 \n: ");
printf("If you would like to exit, enter 0 \n: ");
scanf("%d", &option); // << into the loop
switch (option) {
答案 1 :(得分:1)
在while (option != 0)
处恰好存在无限循环。
您需要修改while
循环。
int option = 1; /* initialisation prevents UB, if you're moving the `scanf` into the loop */
while(option != 0)
{
scanf("%d", &option);
}
注意scanf
返回与成功/失败相对应的值,这也可以放入循环的条件表达式中,这将避免需要不必要的(但仍然有用的)初始化:
int option;
while (scanf("%d", &option) == 1 && option != 0) {
switch (option) { ... }
}
如果您希望逐行处理输入,请考虑如果用户输入无效内容时可能会发生什么,例如当他们输入选项时“无效”。
在第一种情况下,丢弃对应于输入失败的返回值,输入流将保持不变(意味着“无效”留待将来读取),因此将发生不希望的无限循环。
在第二种情况下,不丢弃对应于输入失败的返回值;事实上,它会导致循环终止。您可能希望打印错误消息并重新提示用户进行有效选择,所以这是第三种情况:
int option;
for (int v = scanf("%d", &option); v != EOF && option != 0; v = scanf("%d", &option)) {
if (!v) {
puts("ERROR! Invalid selection; try again...");
scanf("%*[^\n]"); /* This discards the junk... */
getchar(); /* This discards the newline following the junk,
* which is unnecessary in your situation */
continue;
}
switch (option) { ... }
}