EDIT:
void print(const int *v, const int size) {
FILE *fpIn;
fpIn = fopen("char-array.txt", "a");
int i;
if (v != 0) {
for (i = 0; i < size; i++) {
printf("%d", (int)v[i]);
fprintf(fpIn, "%d\n", (int)v[i]);
}
perm_count++;
printf("\n");
}
fclose(fpIn);
}
我想这是一个相对简单的问题:)
基本上,该程序使用置换算法,并将输出打印到控制台中的标准输出。我还想通过我假设的 fprintf 将内容写入文件。虽然我似乎无法让它工作。它只是将垃圾字符打印到文本文件的第一行,仅此而已!
我将粘贴下面的代码,非常感谢您的帮助!写入文件代码可在 print 函数中找到。
谢谢,
T。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <time.h>
clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf("%2.3f seconds used by the processor.", ((double)stopm- startm)/CLOCKS_PER_SEC);
int perm_count = 0;
void print(const int *v, const int size) {
FILE *fpIn;
fpIn = fopen("char-array.txt", "wb");
int i;
if (v != 0) {
for (i = 0; i < size; i++) {
printf("%d", (char)v[i]);
fprintf(fpIn, "%d", v[i]);
fprintf(fpIn, "\n");
}
perm_count++;
printf("\n");
}
}
void permute(int *v, const int start, const int n) {
int i;
if (start == n-1) {
print(v, n);
}
else {
for (i = start; i < n; i++) {
int tmp = v[i];
v[i] = v[start];
v[start] = tmp;
permute(v, start+1, n);
v[start] = v[i];
v[i] = tmp;
}
}
}
int main() {
int i, x;
printf("Please enter the number of terms: ");
scanf("%d", &x);
int arr[x];
printf("Please enter the terms: ");
for(i = 0; i < x; i++)
scanf("%d", &arr[i]);
START
permute(arr, 0, sizeof(arr)/sizeof(int));
STOP
printf("Permutation Count: %d\n", perm_count);
PRINTTIME
return 0;
}