2013-09-07 9 views
0

Хорошо, поэтому я получаю «ошибку: ожидаемое первичное выражение перед« ДЕЙСТВИТЕЛЬНЫМ »токеном» в строке, где указан мой оператор printf. Я исследовал эту проблему и до сих пор не понял, что происходит. Если вам интересно, какая моя программа должна быть, кстати, я пытаюсь рассчитать среднее различие во времени, которое требуется, чтобы найти самый частый элемент в массиве с целым числом, используя два разных метода. Первый метод - это только метод грубой силы 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; 
} 
+0

Почему вы включаете как '', так и' '? –

ответ

1

Попробуйте так:

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); 
+1

Кроме того, «% c», вероятно, не то, что вы имеете в виду, и вместо этого следует использовать «% u». –

0

Основная проблема заключается в том, что строковые литералы не охватывают несколько строк. Вы можете процитировать каждую строку, как предположил Мачей. Другой способ решения этой проблемы заключается в использовании \ в конце каждой строки:

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); 

Обратите внимание, что этот метод сохраняет пробелы в строке, которая может быть удобно в зависимости от вашего сценария использования.

+2

Я думаю, что с помощью этого метода в полученной строке будут сохранены пробелы, являющиеся частью отступа. –

+0

@MaciejStachowski хорошая точка, время, чтобы добавить редактирование! – greatwolf

Смежные вопросы