使用结构,无法打印代码中的房屋数量
问题描述:
我的printf都在工作,除了2.我有的问题是为什么我的if语句不打印任何东西,但0?在我使用的.txt文件中,我将它标记为house,因为我标记了它,我只是好奇,如果有人能告诉我为什么我只能得到0作为值。使用结构,无法打印代码中的房屋数量
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct properties
{
int properties;
char type[20];
float rcost;
float mcost;
int bedrooms;
int bathrooms;
};
typedef struct properties p;
int main(int argc, char *argv[])
{
FILE *ifp;
p A[50];
p B[50];
int n;
int m;
if (argc == 2)
{
if (ifp = fopen(argv[1], "r"))
{
fscanf(ifp, "%d", &n);
int i;
int house = 0;
int house1 = 0;
int house2 = 0;
float totalrent = 0;
float totalrentA = 0;
float totalrentB = 0;
float averagecostA = 0;
float averagecostB = 0;
float totalcost = 0;
float averageprice = 0;
for (i = 1; i <= n; ++i)
{
fscanf(ifp, "%s", &A[i].type);
fscanf(ifp, "%f", &A[i].rcost);
fscanf(ifp, "%f", &A[i].mcost);
fscanf(ifp, "%d", &A[i].bedrooms);
fscanf(ifp, "%d", &A[i].bathrooms);
totalrentA += A[i].rcost;
averagecostA = A[i].rcost/A[i].bedrooms;
if (A[i].type == "house")
{
house1 += 1;
}
//printf("%s\n", A[i].type);
//printf("%.2f\n", A[i].rcost);
//printf("%.2f\n", A[i].mcost);
//printf("%d\n", A[i].bedrooms);
//printf("%d\n", A[i].bathrooms);
}
printf("Total income Owner 1: $%.2f\n", totalrentA);
fscanf(ifp, "%d", &m);
for (i=1; i <= m; ++i)
{
fscanf(ifp, "%s", &B[i].type);
fscanf(ifp, "%f", &B[i].rcost);
fscanf(ifp, "%f", &B[i].mcost);
fscanf(ifp, "%d", &B[i].bedrooms);
fscanf(ifp, "%d", &B[i].bathrooms);
totalrentB += B[i].rcost;
totalcost += B[i].mcost;
averagecostB = B[i].rcost/B[i].bedrooms;
averageprice = (totalrentA + totalrentB)/(n + m);
if (B[i].type == "house*")
{
house2 += 1;
}
//printf("%s\n", B[i].type);
//printf("%.2f\n", B[i].rcost);
//printf("%.2f\n", B[i].mcost);
//printf("%d\n", B[i].bedrooms);
//printf("%d\n", B[i].bathrooms);
}
printf("Total cost Owner 2: $%.2f\n", totalcost);
printf("Average price per bedroom Owner1: $%.2f\n", averagecostA);
printf("Average price per bedroom Owner2: $%.2f\n", averagecostB);
printf("# of houses Owner1: %d\n", house1);
printf("# of houses Owner2: %d\n", house2);
printf("Average price of all properties: $%.2f\n", averageprice);
}
}
else
{
printf("Correct Usage: ./<exec> <infile>\n");
exit(1);
}
return 0;
}
答
我认为它好懂什么在主要通过(INT ARGC,CHAR *的argv []),如果你在代码中使用它。 “argc是从命令行传入程序的参数个数,argv是参数数组。换句话说,argc是argv的数量,所以你的第一个条件if(argc == 2)基本上检查命令行的参数是否为2,我不认为这是你的意图。在大多数情况下(或者默认情况下),参数是1,它的值是你的目录。
在第二个if条件中,您尝试使用fopen传递argv [1]作为文件名打开文件。这是有效的,但我建议你先检查argv [1]的确是你的文件名,而不是NULL。 我不知道你是否注意到,但你的for循环从2开始,因为++我会增加它之前,不像我++是后增量影响起点和终点
“为什么不会我的if语句打印“if”语句不用于打印;使用'printf'或类似的函数。 – Olaf
我说我的问题错了,我试图弄清楚的是,我的语法不正确,从.txt文件中获取我想要的值,因为我的house1和house2值只能作为0. – Maxsensa
为什么不启动调试器并看看你自己。 – Olaf