asked on # Finding Divisors

In the code below it is not registering float values - for example if it divides 4 by 3 it is registering 1 as an answer (if you enter 4 when it loops up to 3 it doesn't record the float value).

I want to store the float value so I can see if it is a divisor or not.

I want to store the float value so I can see if it is a divisor or not.

```
#include <iostream>
#include <cmath>
bool is_integer(float number) {
return std::floor(number) == number;
}
int divisors(int number) {
int i = 1;
float result;
for (i = 1; i<= number; i++) {
result = number / i;
std::cout << i;
std::cout << result;
std::cout << "\n";
}
}
int main()
{
int counter = 1;
int number;
int number_divisors;
std::cout << "Enter a number to find the divisors";
std::cin >> number;
number_divisors = divisors(number);
return 0;
}
```

C++

Integer math will do this job faster than floating point. Only numbers up to the square root of the number under test must be examined. Example pseudocode below ...

```
for k = 2 to sqrt(testnumber)
if [testnumber mod k) == 0] {
print (k, "is a factor of", testnumber)
print (testnumber/k, "is a factor of", testnumber)
}
next k
```

result = number / i;you could make it 2 statements as suggested by phoffric or do

```
result = ((float)number )/ i;
```

this would 'cast' the nominator to float and the division result is float as well.

Sara

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst

William Peck

```
number_divisors = divisors(number);
```

you seem to be expecting divisors() to return something but I don't see a return statement in the function.

```
float result;
for (i = 1; i<= number; i++) {
result = number / i;
std::cout << i;
std::cout << result;
std::cout << "\n";
}
}
```

also if you are trying to count divisors the logic you've used is not going to do any counting..... for that you have to do what Dr.Klahn has suggested

Log in or sign up to see answer

Become an EE member today7-DAY FREE TRIAL

Members can start a 7-Day Free trial then enjoy unlimited access to the platform

or

Learn why we charge membership fees

We get it - no one likes a content blocker. Take one extra minute and find out why we block content.

Not exactly the question you had in mind?

Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.

ask a question
Try using f instead of number when calculating result.