adjust list by normalizing

For this program I need to alter the values in a vector by dividing all of them by the max value. The input will start with the number of elements in the vector and the output should be a floating point value with two integers following the decimal.

issue:
the first input is not being read but the last value is read and output twice

eg.
input :
4 30.0 50.0 10.0 100.0

expected output:
0.30 0.50 0.10 1.00

current output:
0.50 0.10 1.00 1.00

current code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
   vector<float>Input;
   int numInput;
   float currVal;
   int i;
   int j;
   float maxVal;
   
   cin >> numInput;
   cin >> currVal;
   
   for (i = 0; i < numInput; ++i ){
      cin >> currVal;
      Input.push_back(currVal);
   }
   maxVal = Input.at(0);
   
   for (j = 0; j < numInput; ++j ){
      if (Input.at(j) > maxVal){
      maxVal = Input.at(j);
      }
   }
   cout << fixed << setprecision(2); 
   
   for (i = 0; i < numInput; ++i ){
      cout << Input.at(i)/maxVal << " ";
    }
   
   cout << endl;

   return 0;
}


Last edited on
Line 15 burns one of your input values.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>

int main()
{
    std::vector<double>input{4,30.0,50.0,10.0,100.0};
    
    int max = *std::max_element(input.begin() + 1, input.end());
    std::cout << "Max: " << max << '\n';
    
    for(int i = 1; i < input.size(); i++)
        input[i] /= max;
    
    for (auto i = input.begin() + 1; i != input.end(); i++)
        std::cout << *i << ' ';
    
    std::cout << '\n';
    
    return 0;
}


Max: 100
0.3 0.5 0.1 1 
Program ended with exit code: 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
#include <vector>

int main() {
    size_t numInput {};

    std::cout << "Enter how many number: ";
    std::cin >> numInput;

    std::vector<double>Input(numInput);
    double maxVal {};

    std::cout << "Enter " << numInput << " values: ";

    for (auto& n : Input) {
        std::cin >> n;

        if (n > maxVal)
            maxVal = n;
    }

    for (auto& i : Input)
        i /= maxVal;

    std::cout << std::fixed << std::setprecision(2);

    for (const auto& i : Input)
        std::cout << i << ' ';

    std::cout << '\n';
}

Topic archived. No new replies allowed.