还需要一个条件,即用户无法输入高于15的值。 如果用户再次插入相同的六进制,它将重新启动"循环"
int matrixArray[4][4], i, j, rowsum, columnsum, diagonalsum;
printf("Skriv in 16 olika värden för din 4 x 4 kvadrat: "); // asks user to insert 16 numbers to see if its a magicsquare
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
scanf_s("%x", &matrixArray[i][j]); // inserts values into the array
}
}
答案 0 :(得分:0)
我定义了一个&#34;看过&#34;的数组。数字,其中存储用户已输入的数字的0/1标志,如
int seen[16]; // initialize with 0
然后,每次scanf_s
为您提供最新的输入(为简洁起见,我们称之为in
),您可以检查seen[in] == 0
。如果是,只需将号码存储在matrixArray
中,请设置seen[in] = 1
并继续。如果不是,则用户输入了两次号码。只需丢弃输入,给她一个很好的错误信息并继续。这可以在while
循环中完成。
伪代码
ok = false
for i = 1..4 {
for j = 1..4 {
while (not ok) {
in = scanf()
if (not 1 <= in <= 16)
error("input must be between 1 and 16; try again")
continue
if seen[in] == 1
error("you already entered that number; try again")
continue
else
matrixArray[i][j] = in
seen[in] = 1
ok = true
}
}
}
答案 1 :(得分:0)
使用先前读取的值来查找重复项
#define ROW 4
#define COL 4
int total = ROW*COL;
printf("Skriv in %d olika värden för din %d x %d kvadrat: ", total, ROW, COL);
for (int i = 0; i < total; i++) {
bool duplicate;
do {
duplicate = false;
unsigned value;
if (scanf_s("%x", &value) != 1) {
printf("Numeric data not entered\n");
exit(-1);
}
for (int k = 0; k < i; k++) { // look through prior values
int r2 = k/COL;
int c2 = k%COL;
if (value == matrixArray[r2][c2]) {
duplicate = true;
printf("Duplicate\n");
break;
}
}
} while (duplicate); // reject recent entry and try again.
int r = i/COL;
int c = i%COL;
matrixArray[r][c] = value;
}