c - 文件 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);
解决方案
//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);
推荐阅读
- python - 为什么我的矩形不出现(python 3.8 windows 7)
- javascript - 为什么这个计时器脚本不能按预期工作?
- flutter - 如何使用异步方法返回的值初始化小部件状态中的字段?
- python - “树视图焦点”时如何将图像表单数据库检索到标签?
- android - 如何实现 WhatsApp 之类的图片点击功能
- flutter - Flutter:计算两个日期之间的月差
- excel - Excel 合并数据不工作 - 数据不合并
- c# - 如何创建一个方法来创建一个不会重复的唯一编号?
- javascript - 颜色生成器 - 如何将颜色应用于所有按钮?
- ios - Swift Firebase 旧数据在 pushviewcontroller 之后显示