% versus FMOD for calculating modulus [closed]

吃可爱长大的小学妹 提交于 2019-12-10 12:24:38

问题


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:

Thx in advance..


回答1:


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:


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.



回答2:


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.



来源:https://stackoverflow.com/questions/11243632/versus-fmod-for-calculating-modulus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!