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

thu*_*sit 2 c compiler-errors

无法找到错误的东西......

我一直在编程并尝试解决问题,但我找不到错误.你能帮助我建议我在这个程序中编码错误了吗?会很感激:)

这是我编写程序后编译器所说的:

In function 'main':
Line 40: error: invalid lvalue in assignment
Run Code Online (Sandbox Code Playgroud)

这是:

/*Calculate area for single room*/
width * length = totalArea_single;
Run Code Online (Sandbox Code Playgroud)

这是整个代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Igo*_*gor 6

应该

totalArea_single = width * length;
Run Code Online (Sandbox Code Playgroud)

代替

width * length = totalArea_single;
Run Code Online (Sandbox Code Playgroud)


Hem*_*war 5

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

error: invalid lvalue in assignment
Run Code Online (Sandbox Code Playgroud)

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

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

width * length = totalArea_single;
Run Code Online (Sandbox Code Playgroud)

因此,在存储任何值/数据时,您需要在=运算符的左侧设置左值.虽然width*lenght生成一个不能存储任何值的rvalue,但简单来说,你可以说存储你需要lvalue的任何值.这就是你需要将此语句更改为的原因

totalArea_single = width * length;
Run Code Online (Sandbox Code Playgroud)

有关左值和右值的更多详细信息,请参阅此SO 链接.