首页 > 解决方案 > 文件 C 中表的背包问题数据存储

问题描述

我正在尝试从一个文件中存储价值、重量和成本的数据,该文件包含一个表格,该表格包含价值、重量和成本的三列数字。该表的长度可能不同(9 或 21 行),具体取决于用户选择的文件。我在尝试存储此文件中的数据以在蛮力功能中使用以解决问题时遇到问题。这就是我到目前为止所拥有的。

     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
     int main()
     {
         int nr_rows;
         int i = 1;
         int j = 2;
         int k = 3;
         int l,m,n = 0;
         int budget_cost;
         int weight_lim;
         char file_name[50];
         float c[nr_rows][3];
         char stringA[20] = "objectsA.txt";
         char stringB[20] = "objectsB.txt";

         printf("Enter the filename containing item listing: ");
         scanf("%s", &file_name);
         if(strcmp(file_name,stringA)==0)
         {
             nr_rows = 9;
         }
         else if(strcmp(file_name,stringB)==0)
         {
             nr_rows = 21;
         }
         printf("The number of rows is %d", nr_rows);
         float value[nr_rows], weight[nr_rows], price[nr_rows];
         FILE *fpointer;
         fpointer = fopen(file_name, "r");
         if(!fpointer)
         {
             printf("The file %s could not be opened.", file_name);
             return 1;
         }
         j=0;
         while(j<nr_rows)                            
         {                                          
             i=0;                      // Skip the first line
             while(i<3)
             {
                 fscanf(fpointer, "%f", &c[j][i]);
                 //printf("%.0f\n", c[j][i]);
                 if(i=1) /* Change this if statement so that 1 ,4 ,7 ,10
                            etc. activates*/
                 {
                     c[j][i] = v[l];
                     l++;
                     printf("%f", v[l]);
                 }
                 else if(i=2)/* Change this if statement so that 2,5,8 etc. 
                                activates*/
                 {
                     c[j][i] = w[m];
                     m++;
                 }    
                 else if(i=3)/* Change this if statement so that 3,6,9 etc. 
                                activates*/
                 {
                     c[j][i] = p[n];
                     n++;
                 }
                 i++;
             }
             j++;
         }
         fclose(fpointer); 

标签: cfilecomputer-sciencefile-handlingknapsack-problem

解决方案


//1. Read carefully your file name by doing:
scanf("%s", file_name); // instead of scanf("%s", &file_name);

//2. Declare  c[nr_rows][3] only after reading "nr_rows"

//3. The main "while" loop could look like this
while(j < nr_rows)
{
    fscanf(fpointer, "%f %f %f", &c[j][0], &c[j][1], &c[j][2]);
}
// Then,
fclose(fpointer);

推荐阅读