運行下面的代碼
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
while(cin>>n) {
double result = log(n)/log(3);
cout<<result<<endl;
cout<<(int)result<<endl;
}
return 0;
}
輸入253,結果輸出
5
4
懷疑由於計算精度丟失所以result並不是5而是小於且很接近5的一個數,但輸入的時候顯示5,因此取整數部分爲4。
下面利用代碼驗證一下
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
while(cin>>n) {
cout<<n<<endl;
}
return 0;
}
輸入4.99999999999999
結果輸出5。說明那個result的確是一個小於5但很接近5的數。
將代碼改一下,就能判斷一個double類型的數是否整數
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
while(cin>>n) {
if(abs(round(n) - n) < 0.000000000000001) {
cout<<"is an integer"<<endl;
} else {
cout<<"not is an integer"<<endl;
}
}
return 0;
}
本博客已停止更新,轉移到微信公衆號上寫文章,歡迎關注:Android進階驛站