C、如何在for循环中存储值,可以不用数组吗?

标签 c store

作业要求:

程序必须计算房屋的面积 用户必须输入他拥有的房间数量,然后程序必须询问每个房间的长度和宽度。之后程序必须显示房子的表面。没有提供公式,但房间的面积是长*宽。

我的应用程序的问题是,在 for 循环中,每个房间的所有长度和宽度的总和值不会被记住。所以输出是错误的。 不用数组可以完成吗?因为我还没有完成该类(class),并且还有很多其他作业需要完成。 非常感谢。

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

main()
{
int camere,lungime,latime,scamere,i,scamera,scameratotal,scasa,total;


printf("Acest program calculeaza suprafata casei\n");    //this program lists the surface of the house
printf("Cate camere are casa?\n");  // how many rooms do you have?
scanf("%d",&camere);

for(i=0;i<camere;i++)
{

printf("Introduceti lungimea si latimea camerei %d\n",i);   //enter the lenght and width of room %d

scanf("%d %d",&lungime,&latime);


scamera=lungime*latime;    //surface of room %d is lenght*width

printf("Suprafata camerei %d este %d\n",i,scamera);  //states the surface of room %d (1 , 2 or 3 etc.)


total = total + (lungime*latime);   // total that i want the program to remember
scasa=total*camere;                 //surface of the house is total*number of rooms


}

printf("\nSuprafata casei este de %d metri",scasa);  //the surface of the house , bad output , it's not  total(sum of surfaces of each room)*number of rooms
}

最佳答案

int total = 0;

for(i=0;i<camere;i++)
{
//ask length
//ask width
total = total + (length * width);
}

display total

编辑:

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

main()
{
    int length = 0;
    int width = 0;
    int rooms = 0;
    int total = 0;

    printf("Acest program calculeaza suprafata casei\n");
    printf("Cate camere are casa?\n");
    scanf("%d", &rooms);

    for(int i=0;i<rooms;i++)
    {
        printf("Introduceti lungimea si latimea camerei %d\n",i);
        scanf("%d %d",&length,&width);
        total = total + (length * width);
    }

    printf("Suprafata casei este de %d square meter", total);
}

如果这不起作用,可能是在使用 scanf 时出现错误,但从未使用过它

关于C、如何在for循环中存储值,可以不用数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26782464/

相关文章:

python - 制作 "durable"对象

c# - 从 Azure 表存储中检索随机行?

javascript - reducer - 添加新元素

c - 初始化指针时的数据类型警告

c - 如何将 char 指针值分配给整数/char 变量或数组

c# - 从 C# .NET 调用使用 C 样式数组作为参数的 C 方法

model-view-controller - ExtJS 4 MVC ComboBox 通过 Direct Store 加载 - 单击组合框时如何防止加载?

java - CRC Craking 知晓结果

c - 为什么 `const` 限定符在此初始化中被丢弃?

android - 在移动应用程序中存储数据的最佳方式