【发布时间】:2026-01-13 07:15:02
【问题描述】:
所以我最初使用#define 编写程序,因为我知道它是作为预处理器发生的,但我的老师评论说我应该使用 const。我尝试在我的代码中替换#define,但它只是破坏了它,我不知道为什么。我知道 const 可以像变量一样使用,所以我的代码应该只是调用它并且会得到相同的结果,不是吗? 这是我的代码有效和无效的屏幕截图 这是工作:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
//Set constant.Preprocessor for speed repace LENGTH
//With what ever number of digits you would want.
#define LENGTH 4
//Converts the input number into an array of digits
int * digitArray(int number) {
//Creating an array for all digits of the constant length
static int digits[LENGTH];
//Loop through the digits and use the mod operator to get each one of them
for(int i = LENGTH-1; i >= 0; i--) {
digits[i] = number % 10;
number = number / 10;
}
//Finally, return the array pointer
return digits;
}
//Compares the correct number array with the guess array of digits, checking for fermi/pica hints and returns
//the number of exact matches of both arrays
int checkGuess(int *num, int *guess) {
//Create two bool arrays to flag the digits already used
bool usedNum[LENGTH] = {false};
bool usedGuess[LENGTH] = {false};
//First loop to check for number of matches
int matches = 0;
int used = 0;
for(int i = 0; i < LENGTH; i++) {
//Check if the digit is the same for both arrays at i index
if(num[i] == guess[i]) {
//If so there is an exact match
usedNum[i] = true;
usedGuess[i] = true;
matches++;
used++;
}
}
而且不工作:
const int LENGTH = 4;
//Converts the input number into an array of digits
int * digitArray(int number) {
//Creating an array for all digits of the constant length
static int digits[LENGTH];
//Loop through the digits and use the mod operator to get each one of them
for(int i = LENGTH-1; i >= 0; i--) {
digits[i] = number % 10;
number = number / 10;
}
//Finally, return the array pointer
return digits;
}
//Compares the correct number array with the guess array of digits, checking for fermi/pica hints and returns
//the number of exact matches of both arrays
int checkGuess(int *num, int *guess) {
//Create two bool arrays to flag the digits already used
bool usedNum[LENGTH] = {false};
bool usedGuess[LENGTH] = {false};
//First loop to check for number of matches
int matches = 0;
int used = 0;
for(int i = 0; i < LENGTH; i++) {
//Check if the digit is the same for both arrays at i index
if(num[i] == guess[i]) {
//If so there is an exact match
usedNum[i] = true;
usedGuess[i] = true;
matches++;
used++;
}
}
我知道这是对其他一些问题的重复,但我没有看到任何具体说明为什么它在这种情况下不起作用以及如何修复它以便代码运行的答案。
【问题讨论】:
-
是的@a.Li 有点像,但老师说我们必须使用“类常量”所以我仍然很困惑,因为如果我正确理解该链接,这将永远无法工作。
-
你的老师不懂 C(并且可能错误地认为它像 C++),因为
const和#define在 C 中根本不能互换。 -
因为它使用了多个数组边界,我认为
#define LENGTH 4是一个很有争议的定义。
标签: c constants c-preprocessor