天天看點

資訊學奧賽一本通 1040:輸出絕對值 | OpenJudge NOI 1.4 02

【題目連結】

ybt 1040:輸出絕對值

OpenJudge NOI 1.4 02:輸出絕對值

【題目考點】

1. if…else語句

2. - 運算符

-x

表達式的值為x的相反數

3. 三目運算符?:

4. fabs()函數 (存在于< cmath >中)

double fabs(double x);

求浮點數x的絕對值

【題解代碼】

解法1:用if…else語句

#include<bits/stdc++.h>
using namespace std;
int main()
{
    double x;
    cin>>x;
    if(x >= 0)
    	cout<<fixed<<setprecision(2)<<x;
    else
    	cout<<fixed<<setprecision(2)<<-x;
    return 0;
}
           

解法2:用if語句

#include<bits/stdc++.h>
using namespace std;
int main()
{
    double x;
    cin>>x;
    if(x < 0)
    	x = -x;
    cout<<fixed<<setprecision(2)<<x;
    return 0;
}
           

解法3:用三目運算符

#include<bits/stdc++.h>
using namespace std;
int main()
{
    double x;
    cin>>x;
    cout<<fixed<<setprecision(2)<<(x >= 0 ? x : -x);//此處條件不能寫x > 0,因為當x為0時,輸出-x會輸出-0.00。本題要保證當x為0時輸出0.00
    return 0;
}
           

解法4:用fabs()

#include<bits/stdc++.h>
using namespace std;
int main()
{
    double x;
    cin>>x;
    cout<<fixed<<setprecision(2)<<fabs(x);
    return 0;
}
           

繼續閱讀