C++ - cout将两个整数的商打印为零

mat*_*w3r 0 c++ integer numbers cout

我在一个文件中读到ifstream,并且我想写出cout已经读取了多少文件,以百分比表示.

long length = 0, now = 0;
int i = 0;
double d = 0;

file.seekg( 0, std::ios::end );
length = file.teelg();
file.seekg( 0, std::ios::beg );

while ( std::getline( file, buffer ) ) {
    now = file.teelg;

    i = now / length * 100;
    d = now / length * 100;

    std::cout << length << " "      // working
              << now << " "     // working
              << ( now / length * 100 ) << " "  // not working = 0
              << i << " "           // not working = 0
              << d;         // not working = 0
}
Run Code Online (Sandbox Code Playgroud)

只有当now = length我看到它的时候100%,但每隔一段时间它就会失败并让我回来0.我可以想象,答案很简单1*1,但现在我找不到解决方案了.我也试过铸造,也许是因为这是问题,但当然没有.

Dar*_*con 6

除非操作数中的一个是floatdouble,/确实整数除法,并丢弃其余部分.

写这样:

( (double)now / length * 100 )
Run Code Online (Sandbox Code Playgroud)


dje*_*lin 6

如果length > now那么now / length整数除法为零.投两双.