if, else if, else function isn't accurately displaying results - c++

#include <iostream>
using namespace std;
// prototype functions
void DisplayResult(float MaxOrMin);
float FindMinimum(float Array[5]);
float FindMaximum(float Array[5]);
//Global Variables
float Array[5];
float MaxOrMin = 3;
float FindMin;
float FindMax;
//Main Function
int main()
{
cout << "Please enter 5 numbers: " << endl;
for (int i=0; i<5; i++)
{
cin >> Array[i]; // input for array
}
cout << "Please enter '0' for minimum or '9' for maximum:" << endl;
cin >> MaxOrMin; // input 0 or 9 for min or max
//Calling Functions
FindMinimum(Array);
FindMaximum(Array);
DisplayResult(MaxOrMin);
return 0;
}
//Function to find Minimum
float FindMinimum(float Array[5])
{
float FindMin = Array[0];
for (int y=1;y<5;y++)
{
if(Array[y] < FindMin)
FindMin = Array[y];
}
return FindMin;
}
//Function to find Maximum
float FindMaximum(float Array[5])
{
float FindMax = Array[0];
for (int x=1;x<5;x++)
{
if(Array[x] > FindMax)
FindMax = Array[x];
}
return FindMax;
}
This last part is my if, else if, else funtion:
//Function to display minimum or maximum result
void DisplayResult(float MaxOrMin)
{
if (MaxOrMin == 0)
cout << "Minimum is: " << FindMin << endl;
else if (MaxOrMin == 9)
cout << "Maximum is: " << FindMax << endl;
else
cout << "Invalid Input" << endl;
}
My project is to create a program using functions to take user input on a 5 float array. Then find the max and min and display whichever the user asks for.
Here is where my problem comes in. For both max(input 9) and min(input 0) I am getting "0". However any other input correctly returns my "Invalid Input" message.
I'm not getting any errors or warnings or errors at all on eclipse. My professor has told me that my problem was likely with my void function for displaying results. I am hoping someone could point me in the right direction here.
Apologies for my formatting and/or if this question is too basic for this site.

You misunderstand how local and global variables work. Your Find* functions shadow the globals with locals and thus they don't appear to do anything.

The problem is that your FindMinimum() (and the same with FindMaximum()) function compute the minimum (maximum) in a local variable and return it but you, in main() don't receive they in correct variables
So the computed value is lost.
I mean... instead of
FindMinimum(Array);
FindMaximum(Array);
you should write
FindMin = FindMinimum(Array);
FindMax = FindMaximum(Array);

Related

Trouble Implementing Two Vectors MVS C++

Hello Stack Overflow users,
I have this program that i am trying to create for my collection of movies, and please forgive me for some of my mistakes and oversights since I AM NEW TO C++, but basically my program runs (yay) but when I chose any of the four options this error pops up:
Main Error
I want the first program option to display like this:
Akira 10.0
Blade Runner 10.0
Deadpool 8.8
BUT IT DOESN'T DO THAT it just looks like:
10.0
10.0
8.8
Example of my bad output
My output just displays all of the scores on new lines but no movie titles show up and if I try any of the last three options (highest/lowest/average) it just displays the same error: Same error as above
If you could give me any pointers (or a code example) as what I need to do to make the output appear as the bold one above, that would be amazing!
Again please forgive me for possible simple errors I am making since this is my first time working with vectors.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
// Function Prototypes
void displayList(vector<string>,vector<double>);
void highestRating(vector<double>);
void lowestRating(vector<double>);
void averageRating(vector<double>);
// 1st Vector Defintion
vector<string> movies{ // inside this is a list of 48 strings containing movie names (Ex: "Akira", "Blade Runner" };
// 2nd Vector Definition
vector<double> ratings{ // Inside this is a list of 48 doubles that contain movie scores for each movie
and i wish for it to print out directly right of the movie title, then turn to the next line.
Examples of numbers inside this vector: 9.9, 10.0, 5.5, 7.5 };
// Main
int main()
{
cout << fixed << showpoint << setprecision(1);
// Variable Definitions
const int DISPLAY = 1, HIGHEST = 2, LOWEST = 3, AVG = 4;
int response;
cout << "-------Welcome to C++ Newbie's Movie Collection Database-------" << endl;
cout << "\nEnter 1 to display the whole collection" << "\nEnter 2 to display the 5 highest rated movies by me";
cout << "\nEnter 3 to display the lowest 5 rated movies by me" << "\nEnter 4 to display the average score of the movies in the collection along with some other math" << endl;
cin >> response;
// Menu
do
{
switch (response)
{
case(DISPLAY):
{
displayList(movies, ratings);
break;
}
case(HIGHEST):
{
highestRating(ratings);
break;
}
case(LOWEST):
{
lowestRating(ratings);
break;
}
case(AVG):
{
averageRating(ratings);
break;
}
default:
{
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3 || response == 4);
return 0;
}
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val <= movies.size(); ++val)
{
cout << movies[val] << "\t";
for (int rat = 0; rat <= ratings.size(); ++rat)
{
cout << ratings[rat] << endl;
}
}
}
// Display highest by me
void highestRating(vector<double> ratings)
{
double max = ratings[0];
for (int i = 0; i <= ratings.size(); i++)
{
if (ratings[i] >= max)
max = ratings[i];
}
cout << "\nThe highest rated movie is " << max << endl;
}
// Display Lowest by me
void lowestRating(vector<double> ratings)
{
double min = ratings[0];
for (int a = 0; a <= ratings.size(); a++)
{
if (ratings[a] <= min)
min = ratings[a];
}
cout << "\nThe lowest rated movie is" << min << endl;
}
// Average Score by me
void averageRating(vector<double> ratings)
{
double average;
double total = 0;
for (int x = 0; x <= ratings.size(); x++)
{
total += ratings[x];
}
average = total / ratings.size();
cout << "\nThe average is " << average << endl;
double forTheFunOfIt = fmod(average, 2.0);
cout << "\nThe Average divided by 2 is " << forTheFunOfIt << endl;
}
To address your first problem in displayList(), you are displaying a movie, and then looping to display all of the ratings. You probably need to display both within the same single loop. Also, if you do this then you need to make sure that both vectors have the exact same sizes to avoid attempting to access beyond the range of your vector, (it is probably best to use a std::map of movies and rating).
Having said that, for your code above maybe try changing displayList() to something like
// Display List
void displayList(vector <string> movies, vector <double> ratings)
{
for (int val = 0; val < movies.size(); val++)
{
cout << movies[val] << "\t" << ratings[val] << std::endl;
}
}
Note, you are not going to want to loop while val <= movies.size(), the indexes to your vector of (for example) 4 movies and 4 ratings will be 0-3, not 0-4. You will encounter an error indicating you are out of range.
Now for your next problem, you are looping in main() on the initial input from the user, but you are never updating the response variable from a user input. This will cause you to fall into an infinite loop! An easy fix for you will be to move cin >> response into the top of your do-while loop.
Moving onto the next couple issues, which is invalid output for your highest, lowest, and average. Again, you should not be looping while the index is less than or equal to the total size of the vector. Instead, you want less than only.
Lastly, you may want to consider passing your vectors as const references

I Need to Pass Array to a Function to Average Different Test Scores [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
The goal of this code is to pass an array through a function (which I'm already having a difficult time understanding). I went through with a pen and paper and traced the code and I think I just don't know enough to understand what's going wrong. All the test scores I throw in just push back a ridiculously large negative number. I'm not asking for you guys to do my homework because I really want to try and understand what I'm doing, but any help would really be appreciated right now.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
cout << "This program will calculate the average of four diffrent exam scores." << endl;
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
//function implementation
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
First obvious bug:
int studentScores[4]
studentScores has 4 elements, numbered studentScores[0] through studentScores[3].
But your code accesses studentScores[4] in
result = (... + studentScores[4]) / ...
which doesn't exist (and doesn't access studentScores[0], which does).
Glad to try to help ya out without giving you the answer.
I'm gonna sprinkle some questions throughout your code that you should be asking yourself in future programs whenever you get unexpected output.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
/* Above, you declared a string to store the user's input in.
In C++, the string "4" DOES NOT equal the integer 4.
How will you handle the fact that the variable 'score' is of type
string, but you want to work with integers?
Is there an easy way to get rid of this issue? (hint: use cin)
*/
cout << "This program will calculate the average of four diffrent exam scores." << endl;
/* In the below for-loop, think about what the value of 'score' will be
after each iteration. (Hint, getline replaces the existing value of score).
Also, where is the code that saves the user's inputted numbers to an array?
Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/
*/
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
/* In the for-loop below, you already noticed that your array has random
values in it. The comment about the above for-loop should address that issue.
Equally important though is understanding what the heck is happening in this
loop below. After you fix the bug in the for-loop above (which will
get the values in the array to equal the user's inputs), you'll be faced
with issues in this loop below.
My advice is to understand what happens when the program
executes "studentScores[i]++". First, it gets the number in the array at
the ith+1 position, then it increments that number by 1. Cool, but what
are you doing with the result of that? It's not being put to use anywhere.
Also, note that because the array is never being updated,
the line above it just calculates the same number and stores it in 'result'
every iteration of the loop.
*/
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average.
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
I hope these comments helped :) Keep at it!
Don't forget that arrays start at index 0. Trying to access studentScores[4]
will give you an unexpected number.

Creating an array

write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}

My search function in C++ is pulling up all the answers and not a single one

I'm really confused. I have to make this lab for a class and I can't seem to have the search only display one result but all of the months of the year. I also can't seem to figure out why its not displaying the TotalRainfall when I input 0 into the month of the year.
Thank you.
#include <iostream>
#include <fstream>
const int MaxSize = 12; //How many weather lines will be available.
using namespace std;
struct WeatherInformation
{
int Month; //Months of the year
float TotalMonthsRainfall; //Total amount of rainfall
float HighTemp; //The Highest temperature of the month.
float LowTemp; //The Lowest temperature of the month.
float AverageTemp; //The Average temperature of the month.
};
WeatherInformation WeatherArray[MaxSize]; //Declaring a month array of MaxSize
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[]);
void WeatherMonthSearch (WeatherInformation WeatherArray[]);
int main()
{
float TotalRainfall = 0;
int count = 1; //Counts how many times the for loop goes.
int MonthOfWeather; //User input of the month.
char ProgramRedo; //User input if they want to reuse the program.
char exit_char; //User input to exit the program.
ifstream MyinFile; //Variable that uses file.
ReadFile (MyinFile, WeatherArray); //Call ReadFile Function
WeatherMonthSearch (WeatherArray); //Call WeatherMonthSearch Function
MyinFile.close(); //Closes file.
}
//Brett Holmes
//4/30/2013
//PreCondition:You need a file labeled weather.dat
//PostCondition: It puts the file variables into an array.
void ReadFile(ifstream& MyinFile, WeatherInformation WeatherArray[])
{
float TotalRainfall = 0;
char exit_char;
int count = 0;
int Month = 0;
cout << "Your Weather Machine" << endl << endl;
MyinFile.open("weather.dat");
if (!MyinFile)
{ //no
cout << "Can't open input file." << endl; //Tests the right file.
char exit_char; //End Program
cout << "Press any key to exit" << endl;
cin >> exit_char;
}
for(count = 1; count < MaxSize; count++) //Puts the file variables in the array.
{
WeatherArray[count].Month = WeatherArray[count].Month + 1;
MyinFile >> WeatherArray[count].TotalMonthsRainfall;
MyinFile >> WeatherArray[count].HighTemp;
MyinFile >> WeatherArray[count].LowTemp;
(WeatherArray[count].AverageTemp = ((WeatherArray[count].HighTemp + WeatherArray[count].LowTemp)/2));
(TotalRainfall = TotalRainfall + WeatherArray[count].TotalMonthsRainfall);
}
}
//Brett Holmes
//4/30/13
//PreCondition:You need to have the months already put into an array in a struct.
//PostCondition:Outputs the rainfall stats the user puts in then asks to run again.
//Outputs a error message if they type in the month wrong.
void WeatherMonthSearch (WeatherInformation WeatherArray[])
{
float TotalRainfall;
int months;
int MonthOfWeather;
char ProgramRedo;
do
{
bool MonthFound = false;
cout << "Please input the number of the Month. Ex. 1=Jan. 2=Feb. etc \n\n";
cin >> MonthOfWeather;
for(int i = 1; i <= MaxSize; i++)
{
months = WeatherArray[i].Month;
if(months == MonthOfWeather ) //Finds the artist and outputs the results
{
cout << "\nTotal Months Rainfall: " << WeatherArray[i].TotalMonthsRainfall << " \n";
cout << "Highest Temperature: " << WeatherArray[i].HighTemp << " \n";
cout << "Lowest Temperature: " << WeatherArray[i].LowTemp << " \n";
cout << "Average Temperature: " << WeatherArray[i].AverageTemp << " \n";
MonthOfWeather = true;
}
}
if(MonthOfWeather == 0)
{
cout << "The total rainfall for the year is: " << TotalRainfall << ".";
}
if(MonthFound == false)
{
cout << "\nMonth Number error. Month not found. Try again.\n\n";
MonthOfWeather = false;
}
cout << "Would you like to look up another month of weather?\n";
cout << "Enter a 'Y' if yes and 'N' if no.\n";
cin >> ProgramRedo;
}while(ProgramRedo == 'Y');
}
Several obvious problems:
Arrays in C++ is 0-based, so your for loop is off-by-one. In your search function, for(int i = 1; i <= MaxSize; i++) should be for(int i = 0; i < MaxSize; i++). Similarly, in your read function, for(count = 1; count < MaxSize; count++) should be for(count = 0; count < MaxSize; count++) (If you want to skip index 0 because you are using it as a signal value, then you should set MaxSize to 13 and have the loop start at 1.)
Why are you assigning a boolean to MonthOfWeather? Do you mean MonthFound?
You read function is not setting the months correctly. WeatherArray[count].Month = WeatherArray[count].Month + 1; should be WeatherArray[count].Month = count; if you are using a 1-based loop or WeatherArray[count].Month = count + 1; if the loop is 0-based.
You calculated your total rainfall in the read function, but the result is stored in a local variable so it's lost when the read is done. Either make TotalRainfall a global variable or do your calculations in your search function.
There are a lot of redundant variable definitions: for example, your weather data array is a global so there is no reason to actually pass it around; exit_char is declared twice in your read function; the first five lines of your main() declared variables that you never used.
Also, your read function does not actually exit the program on failure - it even still attempts to read from the stream and then call your search function! If error-checking is a requirement, you should either have the read function return a boolean and check that the read function succeeded before calling your search function, or simply call std::exit after that cin >> exit_char;.
So, one problem you have is that you have local variables that appear in multiple places, but appears like you expect them to actually contain the same information.
For example, I see three different TotalRainFall. One in main, which is just there, not used for anything, one in ReadFile which is calculated, and one in WeatherMonthSearch, which is not set to anything.
I suspect you want all three of these to actually do something. One way to achieve that would be to remove the local ones in ReadFile and WeatherMonthSearch, and instead pass in the one from main (as a reference into ReadFile).
There's also a few places where you use variables without initializing them. Make it a habit to initialize EVERYTHING and EVERYWHERE!
Enable warnings in your compiler - if you have any form or reasonably new compiler (gcc or MS Visual Studio of recent vintage), it should tell you at least some of these things.

creating a sum function for summing only part of a vector

Obviously I need a sum function for this and accumulate will not cut it
I need to create program - a vector - with n number of elements the user can prescribe - and the sum function can only sum POSITIVE elements even though the user can enter negative elements as well...
In the computeSum function I also need to add a "success" to the whole group
computeSum (dataVec, howMany, total, sucess);
and create a parameter for people who enter - all negative numbers but want to sum them but are unable to because there are no positive numbers
if (success) {
cout << "The sum is " << total << endl;
}
else {
cerr << "Oops, you cannot add these elements.";
}
So here is what I got
#include <iostream>
#include <vector> // need this in order to use vectors in the program
using namespace std;
int main()
{
vector<double> dataVec;
double i, n, howMany, total;
cout << "How many numbers would you like to put into the vector?";
cin >> n;
dataVec.resize(n);
for(vector<double>::size_type i=0;i < n;i++)
{
cout << "Enter the numbers: \n";
cin >> dataVec[i];
}
cout << "How many POSITIVE numbers would you like to sum?";
cin >> howMany;
cout << computeSum (dataVec, howMany, total);
}
double computeSum (vector<double> &Vec, howMany, total)
{
double total =0;
for(int i=0;i < howMany;i++)
total+=Vec[i];
return total;
}
I also seem to having trouble compiling just this - computeSum() is not being understood in int main(); howMany is not being understood in computerSum(); and on a gloabl scope total() and howMany() are undeclared (I guess that would mean i would need to decalre globally???)
In fact, accumulate will “cut it”, with an appropriate functor that only regards positive values:
int sum_positive(int first, int second) {
return first + (second > 0 ? second : 0);
}
…
std::accumulate(data.begin(), data.begin() + how_many, 0, sum_positive);
Getting on my hobby horse: Boost Range Adaptors. Hits the sweet point with me
#include <boost/range/adaptors.hpp>
#include <boost/range/numeric.hpp>
bool isnatural(int i) { return i>=0; }
using namespace boost::adaptors;
int main(int argc, char** args)
{
static const int data[] = { -130, -1543, 4018, 5542, -4389, 15266, };
std::cout << "sum: " << boost::accumulate(data | filtered(isnatural), 0) << std::endl;
return 0;
}
Output:
sum: 24826
With C++11 awesomeness1 spice:
std::cout << "sum: " << boost::accumulate(data
| filtered([] (int i) { return i>=0; }), 0) << std::endl;
1: to be honest, I really hate the clumsyness of lambda syntax:
having to specify the parameter type always
having to spell out the return statement to
For this scenario, it seems to that filtered([] (i) { i>=0 })
could be figured out by the compiler. Well, perhaps in c++22 :)
Your computeSum() function must appear above your main() function in the source file for it to be in scope. Also in your computeSum() function signature you haven't given types to the howMany and total variables. I'm guessing they should be double howMany and double total?