当我除两个变量时,C 程序输出错误

标签 c math

我正在尝试编写一个程序来输出矩形的高度,方法是让用户输入两个数字(面积和宽度),然后除以两个变量(面积和宽度)以获得高度结果。运行这个程序时,我得到的结果是 0.0000。

我认为这可能与我的 scanf 或 printf 行之一的转换说明符有关。

我刚刚学习 C,所以无法解决问题所在。

#include <stdio.h>

int main()
{
    /* initilize variables (area, width and height) */
    float area, width, height;
    /* assign variables */
    area = 0.0;
    width = 0.0;
    height = 0.0;
    /* Gather user input */
    printf("Enter the area in square metres\n");
    scanf("%f", &area);
    printf("Enter the width in square metres\n");
    scanf("%f", &width);
    /* Height of a rectangle = area/width */
    height = area/width;
    /* Print result */
    printf("The height of the rectangle is: %f", &height);

    return 0;
}

最佳答案

错误在行

    printf("The height of the rectangle is: %f", &height)

应该是高度而不是&height

更改为

    printf("The height of the rectangle is: %f", height)

你就可以开始了。

我已经测试过了,效果很好。

Enter the area in square metres
12
Enter the width in square metres
3
The height of the rectangle is: 4.000000

正如 MartinR 所指出的在问题的评论中,您应该学习使用调试器然后您很快就会看到 height 获得了正确的值。所以这个问题与“除两个变量”无关,只有你的 print 语句是错误的。

关于当我除两个变量时,C 程序输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42606846/

相关文章:

c - 访问指向 union 的指针中的指针

C:范围有问题

c - 在 C 中打印 char[] 的一部分的最简单方法

algorithm - 计算吸收马尔可夫链基本矩阵的最佳迭代方法?

javascript - 将给定观察者位置的太阳路径转换到谷歌地图上

c - 用什么来描述 C 中的指针是一个很好的现实世界隐喻?

c - 从另一个数组内部的数组中检索值 [C]

Javascript Math.cos 和 Math.sin 不准确。有什么解决办法吗?

c - 四元数 "lookAt"函数

math - 排列和紊乱有什么区别?