错误:赋值中的左值无效[in c]

时间:2014-09-14 11:33:29

标签: c compiler-errors

CAN'发现什么错误......

我一直在编程并试图在这里修复问题,但我找不到错误。你能帮助我建议我在这个程序中编码错误了吗?感谢:)

这是编译人员在遵守该计划后所说的:

In function 'main':
Line 40: error: invalid lvalue in assignment

是:

/*Calculate area for single room*/
width * length = totalArea_single;

以下是整个代码:

#include <stdio.h>
#include <stdlib.h>

/*Main function of this program*/
int main()
{
char input[512];/*buffer*/
char roomInput[512];/*buffer*/
int roomCount =0;/*Store number of room*/
int width =0;/*width integer*/
int length =0;/*length integer*/
int room =0;/*To make sure roomCount have to be more than 0*/
int totalArea_single =0;
int totalArea_all =0;  

/*Ask how many room in the house*/
printf("\nHow many rooms in the house?: ");
fgets(input,sizeof(input),stdin);
sscanf(input,"%d",&roomCount);

/*For loop for calculating room area by number of room entered*/
for(room=0;room<roomCount;room++)
{
    /*Input for width and have to be more than 0*/
    while(width>0)
    {
        printf("Width in meters for room %d: ",room+1);
        fgets(roomInput,sizeof(roomInput),stdin);
        sscanf(roomInput,"%d",&width);
    }

    /*Input for length and have to be more than 0*/
    while(length>0)
    {
        printf("Length in meters for room %d: ",room+1);
        fgets(roomInput,sizeof(roomInput),stdin);
        sscanf(roomInput,"%d",&length);
    }

    /*Calculate area for single room*/
    width * length = totalArea_single;

    /*Store area of all rooms*/
    totalArea_all = totalArea_single + totalArea_all;

    width = -1;
    length = -1;
}

/*Print out total areas of the house*/
printf("\nTotal areas of the house is %d square meters",totalArea_all);

return 0;
}

我不确定我做错了什么...感谢您的帮助:)

2 个答案:

答案 0 :(得分:6)

应该是

totalArea_single = width * length;

而不是

width * length = totalArea_single;

答案 1 :(得分:5)

如果您仔细查看编译器错误,可以看到它,它会说

error: invalid lvalue in assignment

因此,为了更好地理解此错误,您必须了解什么是左值右值左值是指超出单个表达式的对象。您可以将左值视为具有名称的对象。另一方面, rvalue 是一个临时值,不会超出使用它的表达式。

因此,如果您查看导致此问题的代码行

width * length = totalArea_single;

因此,在存储任何值/数据时,您需要在 = 运算符的左侧包含左值。 虽然 width * lenght 生成 rvalue ,但无法存储任何值,简单来说,您可以说要存储您需要的任何值左值。这就是您需要将此声明更改为

的原因
totalArea_single = width * length;

有关左值和左值的详细信息,请参阅此 SO Link

相关问题