Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning: conversion to 'double' from 'long int' may alter its value

My code is the following:

#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);

}

I am compiling with

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

and I have some warnings that I need to eliminate. How?

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
like image 372
cateof Avatar asked Oct 08 '22 17:10

cateof


1 Answers

If you don't really need the value rounded to the nearest millisecond - that is, if you can live with an inaccuracy of up to 1 millisecond instead of 1/2 millisecond - you can simply write

mtime = seconds * 1000 + useconds / 1000;

Otherwise, it'll have to be

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

Edit: or not. See comment.

like image 167
Mr Lister Avatar answered Oct 12 '22 11:10

Mr Lister