当输入为2,3,4时,为什么s返回0?

时间:2015-01-18 07:15:32

标签: c floating-point return

#include<stdio.h>
#include<conio.h>

void main(){
  int a,b,c;
  float s,area;

  printf("Enter 3 sides of triangle:");
  scanf("%d %d %d",&a,&b,&c);

  s=(a+b+c)/2;
  printf("%d",s);

  area=sqrt(s*(s-a)*(s-b)*(s-c));
  printf("Area of triangle is : %.1f",area);
}

并解释按位补码运算符为什么〜0是-1?它是如何工作的?

2 个答案:

答案 0 :(得分:2)

因为你正在做整数除法,试试这个

s=((float)(a+b+c)) / 2.0;

如果你没有投出数字

s = (2 + 4 + 3) / 2 -> 9 / 2 - > 4

然后

area=sqrt(4*(4-2)*(4-3)*(4-4));
                      /*  ^ this is 0

因此

area=sqrt(4*2*1*0) -> sqrt(0) -> 0;

正如其他答案已经提到的那样,~按位运算符会翻转它的操作数位,这意味着如果你有数字10它的二进制表示是

00001010
^^^^^^^^   
11110101

如果您在其上应用~运算符,它就会变为

11110101 -> 245 // unsigned

变为245 - 256 = -11,请参阅Two's complement

答案 1 :(得分:0)

  

当输入为2,3,4时,为什么s返回0?

因为您正在进行int计算。

  

并且还解释了按位补码操作符为什么〜0是-1 ??它是如何工作的????

假设8位,0为:

00000000

什么是〜0?

11111111

在Two's中补充它-1,因为如果你翻转所有位并在结果中加1,你就会得到:

00000001

由于MSB为1,结果为负。