无法摆脱C++警告

问题描述 投票:0回答:1

我是 C++ 新手,这个警告让我发疯。

警告 C4244“参数”:从“double”转换为“int”,第 41 行可能会丢失数据

线路是:

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

我检查了我的代码,它似乎与类型一致(就我而言)。我已经清除/重建解决方案,重新启动 VS 几次。

通过简单地删除部分线路,问题似乎就在这里:

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

当我用其他东西替换它时,警告就会消失。除了这个之外我没有其他警告。

有什么细微差别我不明白吗?

这是我的完整代码:

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;
}
c++ types warnings compiler-warnings
1个回答
0
投票

Horner
的定义是

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

double x
作为第三个参数。
sum
的定义是

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

它采用

int
作为第三个参数。

由于您将

x
中的
double
(这是一个
Horner
)传递给
sum
,因此存在
double
int
的类型转换。

© www.soinside.com 2019 - 2024. All rights reserved.