Boolean and Void problem

后端 未结 3 1876
时光取名叫无心
时光取名叫无心 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:00

    You've got return total in a function that returns void. void means that the function returns nothing.

    Methinks you expect return total to update the total parameter in your call, but that's not the way it works.

    Better go back to square one and read about value parameters and function results.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-29 10:19

    The error says it all, you are trying to return a bool from a function with return type void. Change the return type to void.

    About declaring success, simply declare it like every other variable you have declared.

    0 讨论(0)
提交回复
热议问题