酷代码 AI
菜单
全部AI  /  热门  /  AI问答
服务商

#include <stdio.h> #include <stdlib.h> // 函数声明 void findSubsets(int *set, int subset[], int index, int n, FILE *outputFile); int main() { int n; // 从文件中读取集合的大小 FILE *inputFile = fopen("input.txt", "r"); if (inputFile == NULL) { perror("无法打开输入文件"); return 1; } fscanf(inputFile, "%d", &n); fclose(inputFile); // 再次打开文件以读取集合元素 inputFile = fopen("input.txt", "r"); if (inputFile == NULL) { perror("无法重新打开输入文件"); return 1; }

这段代码存在几个问题需要修正: 1. 输入文件处理问题: - 文件指针`inputFile`被关闭后立即重新打开,可能导致性能问题 - 读取集合元素时没有检查读取是否成功 2. 内存管理问题: - 没有检查`malloc`和`calloc`是否分配成功 3. 逻辑问题: - 使用`-1`作为标记值不够健壮,如果集合本身包含`-1`会导致错误 - 空集检查逻辑可以优化 4. 输出格式问题: - 最后一个元素后面会多一个空格 修正后的代码: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> void findSubsets(int *set, bool *included, int index, int n, FILE *outputFile); int main() { FILE *inputFile = fopen("input.txt", "r"); if (inputFile == NULL) { perror("无法打开输入文件"); return 1; } int n; if (fscanf(inputFile, "%d", &n) != 1 || n <= 0) { fprintf(stderr, "无效的集合大小\n"); fclose(inputFile); return 1; } int *set = (int *)malloc(n * sizeof(int)); if (set == NULL) { perror("内存分配失败"); fclose(inputFile); return 1; } for (int i = 0; i < n; i++) { if (fscanf(inputFile, "%d", &set[i]) != 1) { fprintf(stderr, "读取集合元素失败\n"); free(set); fclose(inputFile); return 1; } } fclose(inputFile); bool *included = (bool *)calloc(n, sizeof(bool)); if (included == NULL) { perror("内存分配失败"); free(set); return 1; } FILE *outputFile = fopen("output.txt", "w"); if (outputFile == NULL) { perror("无法打开输出文件"); free(set); free(included); return 1; } findSubsets(set, included, 0, n, outputFile); fclose(outputFile); free(set); free(included); printf("所有非空子集已输出到output.txt文件中。\n"); return 0; } void findSubsets(int *set, bool *included, int index, int n, FILE *outputFile) { if (index == n) { bool isEmpty = true; for (int i = 0; i < n; i++) { if (included[i]) { isEmpty = false; break; } } if (isEmpty) return; fprintf(outputFile, "{"); bool first = true; for (int i = 0; i < n; i++) { if (included[i]) { if (!first) { fprintf(outputFile, " "); } fprintf(outputFile, "%d", set[i]); first = false; } } fprintf(outputFile, "}\n"); return; } // 不包含当前元素 included[index] = false; findSubsets(set, included, index + 1, n, outputFile); // 包含当前元素 included[index] = true; findSubsets(set, included, index + 1, n, outputFile); } ``` 主要改进: 1. 使用`bool`数组代替`int`数组标记元素是否包含在子集中 2. 添加了内存分配和文件读取的错误检查 3. 优化了输出格式,避免多余空格 4. 简化了空集检查逻辑 5. 移除了不必要的文件重新打开操作 6. 使用更清晰的变量名提高代码可读性 [2025-04-02 08:35:29 | AI问答 | 856点数解答]

相关提问