% versus FMOD for calculating modulus [closed]

2019-06-14 18:52发布

My console app looks like that.

#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int a, b;
    cin>>a>>b;
    cout<<"% "<<a%b<<endl<<"fmod "<<fmod(a,b)<<endl;
    system("pause");
    return 0;
}

I'm newbie to C++ and I got 2 questions:

  1. Writing this application on VS. Why do I need to include "stdafx.h"? Is there any requirement? What is this?
  2. Is there any difference between fmod and % ? Getting exactly same results for them:

enter image description here

Thx in advance..

2条回答
聊天终结者
2楼-- · 2019-06-14 19:18

fmod( a , b ) will cast the int variables a and b to floats when the parameters are passed. Depending on the type of a and b (for instance, if you use std::uint64_t) you might lose precision during the cast and get something incorrect returned. The return type will also be a float and will need to be cast again if you're using the function with int types. You should stick to % for int types. Using fmod is less efficient.

查看更多
Melony?
3楼-- · 2019-06-14 19:20

Writing this application on VS. Why do I need to include "stdafx.h"? Is there any requirement? What is this?

Because the default project setting says you need precompiled header (See this).

You can disable this manually. Select Not Using Precompiled Headers as shown in the image below:

enter image description here


Is there any difference between fmod and % ? Getting exactly same results for them:

Yes. % cannot operate on floating-pointer numbers, while fmod can. f in fmod indicates floating-point.

Try this:

float a, b;
std::cin>>a>>b;
std::cout << (a%b) << std::endl; //it will give compilation error.
查看更多
登录 后发表回答