Search code examples
c++typeswarningscompiler-warnings

Can't get rid of the C++ warning


I am new to C++ and this warning has been driving me crazy.

Warning C4244 'argument': conversion from 'double' to 'int', possible loss of data at line 41

The line is:

((x == 1) || (x == -1)) ? (result == sum(coeff, size, x)) : (true);

I have checked my code, it seems consistent with types (as far as I'm concerned). I have cleared/rebuild solutions, restarted VS a couple of times.

By simply removing parts of the line, the issue seems to be here:

(result == sum(coeff, size, x)

When I replace it with anything else, the warning goes away. I have no other warning besides this one.

Is there a nuance I am not understanding?

Here is my full code:

int main() {

    double x = -1;
    const size_t size = 4;
    double coeff[size] = {0};
    cout << Horner(coeff, size, x);

    return 0;
}
#include <iostream>
#include "header.h"
#include <cmath>
#include <cassert>
using namespace std;

void fillArray(double* coeff, size_t size)
{
    srand(static_cast<unsigned int>(time(NULL)));
    double lower_bound = 0;
    double upper_bound = 100;
    for (int i = 0; i < size; i++) {
        coeff[i] = (rand() % 2001 - 1000) / 100.0;
    }
    for (int i = 0; i < size; i++) {
        cout << "Coefficients: " << coeff[i] << " " << endl;
    }
    return;
}
double sum(double* coeff, size_t size, int sign)
{
    size_t s = size;
    double sum = 0;
    for (int i = 0; i < size; i++) {  
        if (s % 2 == 1 || sign == 1) {
            sum = sum + coeff[i];
        } else sum = sum - coeff[i];
        s--;
    }
    return sum; //sum is accurately calculated for x = -1 and x = 1
}
double Horner(double* coeff, size_t size, double x)
{
    fillArray(coeff, size);
    double term = coeff[0];
    for (int i = 0; i < size - 1; i++) {
        term = coeff[i + 1] + term * x;
    }

    double result = term;
    ((x == 1) || (x == -1)) ? (result == sum(coeff, size, x)) : (true);
    return result;
}

Solution

  • The definition of Horner is

    double Horner(double* coeff, size_t size, double x)
    

    which takes double x as the third parameter. The definition of sum is

    double sum(double* coeff, size_t size, int sign)
    

    which takes an int as the third parameter.

    Since you're passing in x (which is a double) in Horner to sum, there's a double to int type conversion.