Exercise 2-10 (SquareFloatvector)
Chapter_2 Exercise_2-9 | ch2-Exercises Chapter_3 |
Exercise 2-10 TCP1, p. 120
Exercise 2-10. Create a vector<float> and put 25 numbers into it as in the previous exercises (Exercise_2-8, Exercise_2-9). Now square each number and put the result back into the same location in the vector. Display the vector before and after the multiplication.
SquareFloatvector.cpp download
// Creating a vector that holds floats, then square its values
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main()
{
float temp;
vector<float> v;
for(float f = 0.0; f < 25; f++) // iterate over float with integer values
{v.push_back(f/2);}
int size = v.size(); // 25
for(int i = 0; i < size; i++)
{
cout << v[i] << ", ";
if (i == size/2) {cout << endl;}
}
cout << endl;
for(int i = 0; i < size; i++)
{
temp = v[i];
v[i] = temp * temp;
}
for(int i = 0; i < size; i++)
{
cout << v[i] << ", ";
if (i == size/2) {cout << endl;}
}
cout << endl;
}
/*
g++ SquareFloatvector.cpp -o SquareFloatvector
./SquareFloatvector
0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6,
6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12,
0, 0.25, 1, 2.25, 4, 6.25, 9, 12.25, 16, 20.25, 25, 30.25, 36,
42.25, 49, 56.25, 64, 72.25, 81, 90.25, 100, 110.25, 121, 132.25, 144,
*/
Chapter_2 Exercise_2-9 | BACK_TO_TOP | ch2-Exercises Chapter_3 |
Comments
Post a Comment