【问题标题】:Why is the output always zero? [closed]为什么输出总是零? [关闭]
【发布时间】:2018-09-19 07:37:11
【问题描述】:
#include <stdio.h>

int main(void)
{
    int a,b,c,t;
    printf("Get the height of the triangle",a);
    scanf("%d",&a);
    printf("Get the base of the triangle",b);
    scanf("%d",&b);
    t=0.5;
    c=t*(a*b);
    printf("The area of the triangle:%d\n",c);
    scanf("%d",&c);
    return 0;
}

在编写代码、编译并执行之后,无论ab的值是否输入,答案始终为零。我想知道为什么,以及如何纠正我的错误。

【问题讨论】:

  • int t; t = 0.5;在你心中是什么意思?
  • 好的,但是t 是一个整数。
  • t 可以持有哪些值?
  • int 不是浮点类型。分配给int 的任何浮点值都将在小数点处被截断并丢失小数点后的所有数字。所以,如果乘法的结果是0.xxxxxxxx,那么整数结果就是0
  • @FredLarson:这实际上并不是问题。

标签: c types area


【解决方案1】:

int 不能保存浮点值。将浮点值分配给 int 将截断小数点处的值。

当您将0.5 分配给t(即int)时,它将被设置为0。将任何内容乘以 0 会得到 0

在执行乘法时,您需要使用浮点数据类型floatdouble,例如:

#include <stdio.h>

int main(void)
{
    int a, b;
    float c, t;
    printf("Height of the triangle: ");
    scanf("%d", &a);
    printf("Base of the triangle: ");
    scanf("%d", &b);
    t = 0.5f;
    c = t * (a * b);
    printf("The area of the triangle: %f\n", c);
    getchar();
    return 0;
}

或者:

#include <stdio.h>

int main(void)
{
    int a, b;
    double c, t;
    printf("Height of the triangle: ");
    scanf("%d", &a);
    printf("Base of the triangle: ");
    scanf("%d", &b);
    t = 0.5;
    c = t * (a * b);
    printf("The area of the triangle: %lf\n", c);
    getchar();
    return 0;
}

【讨论】:

    【解决方案2】:

    't' 变量的数据类型是 int。当您将浮点值分配给变量“t”时,它会在您的情况下被截断,它将被截断为 0。为了获得正确的结果,您期望将 t 变量的数据类型从 int 更改为 float

    【讨论】:

    • 准确地说,变量被截断,而不是四舍五入
    • 是的,我同意
    • 为了迂腐,您不能“将浮点数分配给t”,因为基本类型的赋值表达式仅在 C++ 中是同质的。操作数在之前赋值。在这里真正发挥作用的是这种转换。
    【解决方案3】:

    当您设置t=0.5; 时,您设置了intfloat

    浮点数将被截断为整数部分,这意味着在这里,你得到t=0

    因此,当您乘以 t*(a*b) 时,您乘以 0*a*b 并得到 0。

    使用float t = 0.5 应该没问题。

    【讨论】:

    • 另外,scanf 应该使用 %f 而不是 %d,因为 %d 用于整数,而 %f 用于浮点数。
    • 当我用 %f 替换 %d 时,执行的答案给我 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多