好的,所以我在 printf 语句所在的行上收到“错误:'OTHER' 标记之前的预期主表达式”。我已经研究了这个问题,但仍然没有弄清楚发生了什么。如果您想知道我的程序应该是什么,顺便说一句,我正在尝试使用两种不同的方法计算在整数数组中查找最频繁元素所需的平均时间差。第一种方法只是 O(n^2) 蛮力方法,另一种方法将数组的元素放入二叉树中,同时保留每个元素添加次数的计数器。
#include <stdio.h>
#include <ctime>
#include <time.h>
#include "binArr.h" // Homemade binary tree class with the end of each branch containing a counter
// for how many times it has been reached.
// O(n^2) algorithm: Loop through array and count the number of each element
// by looping through again and checking every other element
// against it, updating, if necessary, a variable for the
// highest count and another for the corresponding element.
int mode (int* arr, int n) {
int most = arr[0];
unsigned mostCnt = 0;
for (unsigned i = 0; i < n; i++) {
int thisCnt = 0;
for (unsigned j = 0; j < n; j++) {
if (arr[j] == arr[i]) thisCnt++;
}
if (thisCnt > mostCnt) {
mostCnt = thisCnt;
most = arr[i];
}
}
return most;
}
void test_efficiency(const unsigned max_array_test_size, const unsigned tests_per_size) {
srand (time(NULL));
double avgTimeDiff = 0;
for (unsigned i = 1; i <= max_array_test_size; i++) {
int arr[i];
for (unsigned j = 0; j < i; j++) {
for (unsigned k = 0; k < tests_per_size; k++) {
for (unsigned m = 0; m < i; m++) arr[m] = rand() % j + 1;
}
clock_t start, stop;
double method1Time, method2Time;
start = clock();
int thisMode = mode(arr, sizeof(arr)/sizeof(int));
stop = clock();
method1Time = (stop - start) / CLOCKS_PER_SEC;
start = clock();
binArr B;
B.addArray(sizeof(arr)/sizeof(int), arr);
thisMode = B.getMost();
stop = clock();
method2Time = (stop - start) / CLOCKS_PER_SEC;
avgTimeDiff += method2Time - method1Time;
}
}
avgTimeDiff /= (max_array_test_size * max_array_test_size * tests_per_size);
printf("After %c tests, testing arrays up to a size of %c, \n
the average time difference between the brute force \n
method and binary tree method to find the mode of \n
an integer array is %f seconds",
tests_per_size, max_array_test_size, avgTimeDiff);
}
int main() {
const unsigned TESTS_PER_SIZE = 500; // Number of tests to be executed
const unsigned MAX_ARRAY_TEST_SIZE = 50; // Array size per test
test_efficiency(MAX_ARRAY_TEST_SIZE, TESTS_PER_SIZE);
/*
int arr[] = {9, 3, 2, 11, 87, 4, 3, 3, 3, 3, 3, 9, 21, 11, 91, 11, 9, 2, 9};
// Using the binary tree
binArr B;
B.addArray(sizeof(arr)/sizeof(int), arr);
std::cout << "The mode of arr, using the binary tree, is " << B.getMost() << std::endl;
// Using the basic O(n^2) algorithm
std::cout << "The mode of arr, using the binary tree, is " << mode(arr, sizeof(arr)/sizeof(int));
*/
return 0;
}