首页 > 解决方案 > C Replacing Variable Number

问题描述

Is it possible to automate this program more in order to change the variable number?

    for (i = 1; i < 4; i++)
    {
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &CodeNumber1);
    printf("Enter the Price for Item #%d: ",i);
    scanf("%f", &Price1);
    printf("Enter the Quantity for Item #%d: ", i);
    scanf("%d", &Quantity1);
    }

So where the variable has 1 written, would it be possible to replace it with i?

Without using an array

标签: c

解决方案


您可以使用数组而不是修复名称。例如,您可以使用类似的东西

int CodeNumber[4] = {0};
for (i = 0; i < 4; i++)
{
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &CodeNumber[i]);
}

在我看来,更好的方法是使用在内部保存 3 个整数的结构:

struct item {
  int CodeNumber;
  int ...
}

然后像这样使用它:

struct item myItem[4];
for (i = 0; i < 4; i++)
{
    printf("Enter the Code for Item #%d: ",i);
    scanf("%d", &(myItem[i].CodeNumber));
    ...
}

推荐阅读