經典算法——求絕對值溢出問題

Problem Description
求實數的絕對值。
Input
輸入數據有多組,每組佔一行,每行包含一個實數。
Output
對於每組輸入數據,輸出它的絕對值,要求每組數據輸出一行,結果保留兩位小數。
Sample Input
123
-234.00
Sample Output
123.00
234.00

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;

int main()
{
	float x;
	float res;

	while (cin >> x)
	{
		res = x>=0 ? x : -1 * x;
		printf("%.2f\n",res);
	}
	return 0;
}

將x,res由float類型改爲double類型就行:

#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;

int main()
{
	double x;
	double res;

	while (cin >> x)
	{
		res = x>=0 ? x : -1 * x;
		printf("%.2f\n",res);
	}
	return 0;
}









發佈了157 篇原創文章 · 獲贊 82 · 訪問量 66萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章