简体   繁体   English

在C ++中无法在计算中获得正确答案

[英]Cannot Get The Right Answer In A Calculation In C++

This is my program for a lab. 这是我的实验程序。 I have to apply two formulas and print answers for both. 我必须应用两个公式并为两个都打印答案。 The first one is in this line: 第一个在此行中:

cout<<"Hypoteneus is: " <<sqrt((x*x)+(y*y)) <<endl;

This one worked. 这个工作了。 The problem is in this one: 问题出在这一个:

cout<<"Area is: " <<a*x <<((1/2)*x*y);

The problem is that it prints its answer as 0. I put the a*x for testing, that worked but the expression (1/2)*x*y is rendering 0 as answer. 问题在于它将答案打印为0。我把a*x进行了测试,它可以工作,但是表达式(1/2)*x*y会将0渲染为答案。 I input x as 1 and y as 2. Please help. 我将x输入为1,将y输入为2。请帮助。

int main ()
{
    float x, y, a=122;
    cout<<"Enter x and y.\n";
    cin>>x >>y;
    cout<<"Hypoteneus is: " <<sqrt((x*x)+(y*y)) <<endl;
    fflush(stdin);
    cout<<"Area is: " <<a*x <<((1/2)*x*y);
    getch();
    return 0;
}

((1/2)*x*y) should be ((1.0/2.0)*x*y) or (0.5*x*y) . ((1/2)*x*y)应该是((1.0/2.0)*x*y)(0.5*x*y)
Otherwise, the compiler will understand int/int and the result will be int so your expected 0.5 will become 0 . 否则,编译器将理解int/int ,结果将为int因此您期望的0.5将变为0

1/2 specifies integer arithmetic, truncating the result to the nearest integer, which is zero. 1/2指定整数算术,将结果截断为最接近的整数零。

Use 0.5f or 1.0f/2.0f for a float constant with the right value. 0.5f1.0f/2.0f用于具有正确值的float常量。 Or divide by two instead of multiplying by a half. 或除以二而不是乘以一半。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM