Boolean and Void problem

后端 未结 3 1877
时光取名叫无心
时光取名叫无心 2021-01-29 09:53

So here is my code a little more edited however now I\'m stuck on the success parameter:

#include 
#include         // need this in         


        
3条回答
  •  日久生厌
    2021-01-29 10:03

    A void return value means the function doesn't return anything. If you want to return total, an int, the return type should be int.

    And, yes, you need to declare variables before you use them. Your main function has no success variable declared and, in fact, it appears to be totally unnecessary anyway.

    I'd consider removing success totally from your code, not passing total to the function (it's unnecessary if you're going to return it), and getting rid of the passed-in howMany - vectors in C++ have a size method which gives you the size of the vector and you can use that within the function.

    And, one more thing, the construct:

    for(int j=0;j < howMany;j++)
        if (Vec[j] > 0){
            total+=Vec[j];
        } else { 
            total+=Vec[j+1];
        }
    

    is not going to behave itself. In cases where an element is not positive, it will add the next element, double counting, and irrespective of its sign.

    You probably need something like (pseudocode):

    for each index:
        if vector[index] > 0:
            add vector[index] to total
    

    This will give you the sum of all positive values, ignoring the negatives totally.

提交回复
热议问题