无法摆脱C++警告

uyhoqukh  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(108)

我是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;
}
b1payxdu

b1payxdu1#

Horner的定义是

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

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

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

它将int作为第三个参数。
由于在Hornersum中传入了x(这是一个double),因此需要进行doubleint的类型转换。

vc9ivgsu

vc9ivgsu2#

有什么细微差别我不明白吗?
编译器警告的原因是在对sum的调用中使用了x

sum(coeff, size, x)
//              ^^^

您可以通过使用int类型的变量并适当地设置其值来删除该警告。

int sign = static_cast<int>(x);

然后使用sum(coeff, size, sign)
您也可以内联static_cast。使用sum(coeff, size, static_cast<int>(x))

免责声明

在发布的代码中还有其他逻辑问题,您可能需要单独解决。

相关问题