经典算法——求绝对值溢出问题

Posted zhihua_bupt

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了经典算法——求绝对值溢出问题相关的知识,希望对你有一定的参考价值。

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;
}


技术分享

技术分享


技术分享















以上是关于经典算法——求绝对值溢出问题的主要内容,如果未能解决你的问题,请参考以下文章