作业要求:
程序必须计算房屋的面积 用户必须输入他拥有的房间数量,然后程序必须询问每个房间的长度和宽度。之后程序必须显示房子的表面。没有提供公式,但房间的面积是长*宽。
我的应用程序的问题是,在 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/