我正在为一个学校项目编写一个程序,用于计算房间的大小并计算油漆、人工等的价格。此函数是用户输入房间尺寸的地方。变量似乎没有正确分配。在主函数中,我将 &
放在参数中的变量旁边,并在此函数中添加了 *
,但这并没有修复程序,我最终收到了错误说:
[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
,您可以简单地使用 break
当if
失败。
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/