怎么编写C程序:从键盘输入一个整数,求其绝对值并输出(提示:使用库函数或使用条件表达式实现)。

如题所述

解:

1、求整数绝对值可以使用库函数abs(int a),返回值就是a的绝对值,注意:abs函数在头文件math中。

2、使用条件表达式使用:a>0?a:a*-1,就是判断a是否大于0,如果是直接返回a,否则返回a的相反数。

参考代码:

#include<stdio.h>
#include<math.h>//引入头文件
int main()
{
    int a,b,c;
    scanf("%d",&a);//键盘输入
    b=abs(a);//方法一求解
    c=a>0?a:a*-1;//方法二求解
    printf("方法一求得绝对值:%d\n;方法二求得绝对值:%d\n;",b,c);
    return 0;
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2010-10-19
#include<stdio.h>
#include<math.h>
int main()
{
int x,y;
printf("请输入整数:");
scanf("%d",&x);
y=abs(x);
printf("绝对值:%d\n",y);
return 0;
}
第2个回答  2010-10-19
#include <stdio.h>
int main()
{
int count;
scanf("%d",&count);
printf("%d",(-1)*count);
getchar();
getchar();
return 0;
}
这样的可以吗?非要用表达式吗?
第3个回答  2010-10-19
#include<stdio.h>
main()
{int x;
scanf("%d",&x);
if(x<0)
x=-x;
printf("%d",x);
}本回答被提问者采纳
第4个回答  2010-10-19
#include <stdio.h>
#include <stdlib.h>

int my_abs(int x)
{
return x>0 ? x : -1*x;
}

int main(int argc, char *argv[])
{
int i;
scanf("%d", &i);
printf("abs(%d) is %d\n", i, my_abs(i));

system("PAUSE");
return 0;
}
相似回答