其他分享
首页 > 其他分享> > c-警告:从“ long int”转换为“ double”可能会更改其值

c-警告:从“ long int”转换为“ double”可能会更改其值

作者:互联网

我的代码如下:

#include <iostream>
#include <sys/time.h>
using namespace std;

int main(int argc, char** argv) {
                if(argv[0])
                        argc++;

                struct timeval m_timeEnd, m_timeCreate, m_timeStart;
        long mtime, alltime, seconds, useconds;

                gettimeofday(&m_timeStart,NULL);
                sleep(3);
                gettimeofday(&m_timeCreate,NULL);
                sleep(1);

        gettimeofday(&m_timeEnd, NULL);
        seconds  = m_timeEnd.tv_sec  - m_timeStart.tv_sec;
        useconds = m_timeEnd.tv_usec - m_timeStart.tv_usec;

        mtime = (long) (((seconds) * 1000 + useconds/1000.0) + 0.5);
        seconds = useconds = 0;
        seconds  = m_timeEnd.tv_sec  - m_timeCreate.tv_sec;
        useconds = m_timeEnd.tv_usec - m_timeCreate.tv_usec;
        alltime = (long) (((seconds) * 1000 + useconds/1000.0) + 0.5);

        printf("IN=%ld ALL=%ld milsec.\n", mtime, alltime);

}

我正在编译

g++ -W -Wall -Wno-unknown-pragmas -Wpointer-arith -Wcast-align
-Wcast-qual -Wsign-compare -Wconversion -O -fno-strict-aliasing

并且我有一些警告需要消除.怎么样?

a1.cpp:21: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:21: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:25: warning: conversion to 'double' from 'long int' may alter its value
a1.cpp:25: warning: conversion to 'double' from 'long int' may alter its value

解决方法:

这应该工作:

mtime = (long)(((long long)seconds*1000000 + useconds + 500)/1000);

始终以相同方式转换表达式.

您看到警告的原因是您的表达式从long转换为double并重新进行数学运算.您可以通过重新整理一下表达式以完全位于整数类型中来避免这种情况.请注意转换成long long以避免溢出(谢谢,Nick).

编辑您可以进一步简化此操作并消除转换:

mtime = seconds*1000 + (useconds + 500)/1000;

标签:g,compiler-warnings,linux,c-4
来源: https://codeday.me/bug/20191201/2083137.html