I got a problem that is not for homework in the book. It states...
"Total Template
Write a template for a function called total. The function should keep a running
total of values entered by the user, then return the total. The argument sent into the
function should be the number of values the function is to read. Test the template in a
simple driver program that sends values of various types as arguments and displays
the results.
(Starting Out with C++: From Control Structures through Objects, 6th Edition. Addison-Wesley/CourseSmart, 03/19/2008. 1024)
"
Here is my code...
#include <iostream>
using namespace std;
template <class T>
T total(int number)
{
T total = 0, aNumber;
for(int count = 0; count < number; count++)
{
cin >> aNumber;
total += aNumber;
}
return total;
}
int main()
{
double totalNum;
int aNumber;
cout << "Enter how many numbers you wish to add up: " << endl;
cin >> aNumber;
totalNum = total(aNumber);
cout << "The total is " << totalNum;
return 0;
}
My question is, if i want the loop to run X amount of times as a paremeter given into the total function, why would i leave that open to anything other than an Int. Could i literally run a loop inside the function a double like 6.7 amount of times? I don't think so, it makes more sense to me that the problem is faulty and i should make a template to add up a various list of numbers that could be anything into a total and return it. So is that not possible or am i not getting the problem.