c - 当我的变量通过 C 中的不同函数传递时,分配不正确

标签 c

我正在为一个学校项目编写一个程序,用于计算房间的大小并计算油漆、人工等的价格。此函数是用户输入房间尺寸的地方。变量似乎没有正确分配。在主函数中,我将 & 放在参数中的变量旁边,并在此函数中添加了 * ,但这并没有修复程序,我最终收到了错误说:

[Error] invalid operands to binary <= (have 'float *' and 'double')

 float areaInput(float* height, float* width, float* length)                   /*recieve pointer value in c function*/
{

    do{
        printf("Please enter the height of the room in metres: ");
        scanf("%f", &height);
        emptyBuffer();
        if (height <= 2.0 || height >= 4.6)
        {
            printf("Please enter a value between 2.1 - 4.5 metres\n");
        }
    }while(height <= 2.0 || height >= 4.6);

    do{
        printf("Please enter the width of the room in metres: ");
        scanf("%f", &width);
        emptyBuffer();
        if (width <= 1.74 || width >= 8.21)
        {
            printf("Please enter a value between 1.75 - 8.2 metres\n");
        }
    }while(width <= 1.74 || width >= 8.21);

    do{
        printf("Please enter the length of the room in metres: ");
        scanf("%f", &length);
        emptyBuffer();
        if (length <= 1.74 || length >= 8.21)
        {
            printf("Please enter a value between 1.75 - 8.2 metres\n");
        }
    }while(length <= 1.74 || length >= 8.21);

}

最佳答案

由于参数是指针,因此需要使用 * 取消引用它们访问值。您也不需要使用&调用scanf()时,因为它需要一个指向存储输入的位置的指针,这就是变量。

而不是在 if 中进行相同的范围测试和do-while ,您可以简单地使用 breakif失败。

float areaInput(float* height, float* width, float* length) /*recieve pointer value in c function*/
{
    while (1) {
        printf("Please enter the height of the room in metres: ");
        scanf("%f", height);
        emptyBuffer();
        if (*height <= 2.0 || *height >= 4.6) {
            printf("Please enter a value between 2.1 - 4.5 metres\n");
        } else {
            break;
        }
    }

    while (1) {
        printf("Please enter the width of the room in metres: ");
        scanf("%f", width);
        emptyBuffer();
        if (*width <= 1.74 || *width >= 8.21) {
            printf("Please enter a value between 1.75 - 8.2 metres\n");
        } else {
            break;
        }
    }

    while (1) {
        printf("Please enter the length of the room in metres: ");
        scanf("%f", length);
        emptyBuffer();
        if (*length <= 1.74 || *length >= 8.21) {
            printf("Please enter a value between 1.75 - 8.2 metres\n");
        } else {
            break;
        }
    }
}

顺便说一句,您的输入验证消息与您正在测试的内容不匹配。如果用户输入高度2.05它将被允许,即使它不在 2.1 之间和4.5 。您假设用户只会在小数点后输入 1 位数字,并且没有考虑到浮点对于许多小数有错误的事实。使用< 2.1而不是<= 2.0 ,例如。

关于c - 当我的变量通过 C 中的不同函数传递时,分配不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000278/

相关文章:

c - crypt() 在 C 中做什么?

c - 以微秒级精度接收 RAW 套接字数据包

你能解释一下为什么 p[-1] 是可能的吗?

c - 在 C 中初始化 struct typedef 数组?

c - 在指向结构的指针上打印错误值

c++ - 如何使用 gnu 缩进在函数名和括号之间设置空格?

c - 如何安装信号处理程序以在收到 'SIGINT' 时调用函数

c - fork 后退出子进程

c - 如何在 Linux 中重新绑定(bind) udp 套接字

c++ - 来自 CMake 的 MSVC 是否与 _MSC_VER 相同?