Arrays & rounding from float to int

I need help getting started here. I am having a wicked brain block. I don't know if the wording is confusing me or what. This is my first experience with arrays.

write a program that takes an array (of any size) of float and
prints its contents to the nearest integer. The rounding should be totally programmed
by you (don't use any C++ special libraries for this).

Write two functions in addition to main:

int roundIt (float x)

which would round any float to the nearest int, and return the int value

and

void print_integers(float a [ ], int size)

which would print/display the contents of array of size size a rounded to the nearest
int.

Your main function could call print_integers, and print_integers would call roundIt
for every element of the array, and print the rounded value.
Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iterator>

int roundIt(float x) {
	return x + 0.5;
}

void print_integers(const float a[], int size) {
	for (int i = 0; i < size; ++i)
		std::cout << roundIt(a[i]) << ' ';

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

int main()
{
	const float data[] {3.1, 4.7, 5, 5.0, 6.1, 6.8, 7.4, 8.5, 9.6};

	print_integers(data, std::size(data));
}


which displays:


3 5 5 5 6 7 7 9 10

This is pointing me in an amazing direction, thank you. Now I am just trying to try to figure out how to get input from the keyboard rather from giving it its parameters.
Maybe something like:

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
#include <iostream>
#include <iterator>

int roundIt(float x) {
	return x + 0.5;
}

void print_integers(const float a[], size_t size) {
	for (size_t i = 0; i < size; ++i)
		std::cout << roundIt(a[i]) << ' ';

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

int main()
{
	const size_t MAX {10};
	float data[MAX] {};
	size_t cnt {};

	std::cout << "Enter a maximum of " << MAX << " numbers (use a non-number to finish): ";
	for (; cnt < MAX && (std::cin >> data[cnt]); ++cnt);

	print_integers(data, cnt);
}



Enter a maximum of 10 numbers (use a non-number to finish): 1.1 2.8 3.4 6.7 q
1 3 3 7

Last edited on
is there a way to ask for any size of an array? I know that is usually done as a parameter to a function - like the part above - when I print this version, it was also printing the 10. If I leave the braces empty, it makes the MAX undefined....
so I got this for the last part - technically it works....
thanks for pointing me in the right direction, I really appreciate it

const int ENTRY = 10;
float data[ENTRY];
int size{};

cout << "Enter a decimal number, enter a character to exit ";
for (; size < ENTRY && (cin >> data[size]); ++size);

print_integers(data, size);
Topic archived. No new replies allowed.