I want to divide a number x with a number from the array[] = {2,3,4,5,6,7,8,9}, so that the result is a clean number (non floating point number such as 1, 2 or 1033), I would like to avoid a result with decimal places (such as 1.23 , 535.222 or 111.111).
Example: x = 140
Which is the biggest number that can divide 140, so that the result is a non floating point number (an int)? Right It´s 7.
Which c method or procedure can I use?
Noting, because I don´t get a solution or any useful idea.
CodePudding user response:
You want to use the div( int numerator, int denominator)
function. It returns a quotient and remainder for the division. If the remainder is zero then the numerator is perfectly divided by the denominator.
bool divides_perfectly( int numerator, int denominator )
{
return ( div(numerator, denominator).rem == 0 )
}
CodePudding user response:
You might want to study this :
- the C way of handling arrays of varrying length (std::vector)
- make functions (to keep code readable)
- never trust your input and do error handling (exceptions in this case)
- use the standard library for common algorithms (like sorting)
- use range based for loops (to not go out of bounds of an array, prevents bugs)
- modulo operator, %, which will give you the remainder of a division
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
#include <stdexcept>
int greatest_divisor(const int value, std::vector<int> divisors) // explicitly copy values
{
std::sort(divisors.begin(), divisors.end(), std::greater<int>());
for (const int divisor : divisors)
{
if (value % divisor == 0) return divisor;
}
throw std::invalid_argument("no valid divisor found");
}
int main()
{
std::vector<int> values{ 2,3,4,5,6,7,8,9 };
int input_value{ 140 };
try
{
auto divisor = greatest_divisor(input_value, values);
std::cout << divisor;
assert(divisor == 7);
}
catch (const std::exception& e)
{
std::cout << "error : " << e.what();
}
return 0;
}