0

I have a little problem with check for multiplicity for 3. It says that my arr must be integer, but in objective I need to have a float massive. How to make this check "arr[i] % 3 == 0" for float numbers.

thanks.

#include <iostream>
#include <cmath>

using namespace std;

float minElement(float arr[], int length) {

    float minElement = arr[0];

    for (int i = 0; i < length; i++)
    {
        if (minElement > arr[i])
            minElement = arr[i];
    }

    return minElement;
}

float multiplyArr(float arr[], int length) {

    float multiply = 1;

    for (int i = 0; i < length; i++)
    {
        if (arr[i] != 0 && arr[i] % 3 == 0)
        multiply *= arr[i];
    }

    return multiply;
}

int main()
{
    float length;
    cout << "Enter integer value: ";
    cin >> length;

    float* p_darr = new float[length];

    cout << "Enter values: " << endl;
    for (int i = 0; i < length; i++) {

        cin >> p_darr[i];
    }

    cout << "Max. element: " << minElement(p_darr, length) << endl;
    cout << "Multiply:  " << multiplyArr(p_darr, length) << endl;

    delete[] p_darr;
    return 0;
}
  • 1
    Does this answer your question? [Why does modulus division (%) only work with integers?](https://stackoverflow.com/questions/6102948/why-does-modulus-division-only-work-with-integers) – scohe001 May 19 '20 at 18:26
  • Why do you need to use a float? Keep in mind that a float actually has less precision for exact values than an int. https://stackoverflow.com/questions/12442685/can-a-ieee-754-real-number-cover-all-integers-within-its-range – Retired Ninja May 19 '20 at 18:28
  • [`std::fmod`](https://en.cppreference.com/w/cpp/numeric/math/fmod) and doing some reading about _comparing floating points for equality_ might help. – Ted Lyngmo May 19 '20 at 18:37
  • what are you trying to do ? Where is `arr[i] % 3 == 0` from ? Do you want to multiply every third number together ? If not, what problem are you trying to solve ? – Jeffrey May 19 '20 at 22:30

1 Answers1

2

Assuming

float massive

to mean "large value". You cannot perform this operation, as it would be meaningless. Comments (and other answers) will suggest fmod. I'll advise against.

If I give you the value 3.6x10^12 and ask you what's the remainder after division by 3, you can't give me a meaningful answer.

3600000000000 % 3 is 0. 3600000000001 % 1 is 1. 3600000000002 % 2 is 2.

But all three values are 3.6x10^12.

If you need integer modulo values, it typically means you need integer precision. Float values won't offer it.

Rather, you should read your input as a string, parse it character by character, and compute the modulo so far. This is a typical first assignment in a computer theory class (as I used to TA).

Jeffrey
  • 11,063
  • 1
  • 21
  • 42