940
魔獸
setiosflags() 的好處多多
本課講:setiosflags( ios::fixed ),其頭文件為:include<iomanip>.
注:在遇到要計算浮點數且希望能控製其輸出、精度、小數點後的位數等時,那麼這個時候,用setiosflags( ios::fixed )來控製是再好不過了!且看下麵程序:
#include<iostream>
#include<cmath>
using namespace std;
int main() {
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
}
輸出結果為:sqrt(2000) = 44.7214. 那麼也就是說編譯器的默認精度為小數點後4位。那麼如果我想讓其小數點後精度為1位、2位、3位或20位,該怎麼辦呢?來,這麼試試:
例一:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
cout << setprecision( 1 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為4e+001
例二:
int main() {
cout << setprecision( 1 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為45
例三:
int main() {
cout << setprecision( 3 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為44.7
大家可以明顯看到,編譯器輸出的結果純粹是無稽之談!根本不是按照人們的意誌去做的!遇到這種比豔門照還尷尬的情況該怎麼辦呢?不要怕,這時候動動腦子,救星就來啦!它就是人稱一朵犁花壓海棠的:setiosflags( ios::fixed ) ! 廢話少說,拿實例來!
例一:
int main() {
cout << setiosflags( ios::fixed ) << setprecision( 1 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為44.7
例二:
int main() {
cout << setiosflags( ios::fixed ) << setprecision( 2 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為44.72
例三:
int main() {
cout << setiosflags( ios::fixed ) << setprecision( 3 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果為44.721
Apparently, all of the answers are totally correct with any doubt! 結果全部正確,哪怕你來個 setiosflags( ios::fixed ) << setprecision( 1000 ), 結果照樣不來半點寒煳!
此外,還要補充一點的是,某些人,當吃飽撐得在床上直打滾兒、嗷嗷叫著難受時,便喜歡多惹出點事非來,他們喜歡在setiosflags()裏再加個showpoint,我不知道這樣做好是不好,可我感覺它確實有點多餘!因為加不加showpoint幾乎是沒什麼區別,如果你也吃多了,肚子漲,胃痛胃酸不消化,非要挑骨頭撿刺兒,那也能找出點不一樣,就是:當setprecision()的精度為0的時候,你有showpoint,那結果你就會多個點兒,沒showpoint,就沒有。實例:
int main() {
cout << setiosflags( ios::fixed ) << setprecision( 0 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} // 結果 45
int main() {
cout << setiosflags( ios::fixed|ios::showpoint ) << setprecision( 0 );
cout << "sqrt(2000) = " << sqrt( 2000 ) << endl;
return 0;
} //結果 45.
看到這個點兒沒?所以說嘛,showpoint,可有可無!如果想簡化程序,那幹脆就不加!
最後,再次特別提醒大家,想使用setiosflags或者setprecision時,一定得加頭文件<iomanip>,在setiosflags()裏麵填東西的時候,前麵一定得加上域符 ios::。
最後更新:2017-04-02 22:16:40