是否可以更多地自动化该程序以更改变量号?
matches
因此,如果变量的写入为1,是否可以用i替换它?
不使用数组
答案 0 :(得分:3)
您可以使用数组而不是修复名称。 例如,您可以使用类似
的内容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));
...
}
答案 1 :(得分:3)
没有阵列?接受挑战。好事Boost.Preprocessor也适用于C!
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/cat.hpp>
#define LOOP_BODY(z, n, data) \
printf("Enter the Code for Item #%d: ", n); \
scanf("%d", &BOOST_PP_CAT(CodeNumber, n)); \
printf("Enter the Price for Item #%d: ", n); \
scanf("%f", &BOOST_PP_CAT(Price, n)); \
printf("Enter the Quantity for Item #%d: ", n); \
scanf("%d", &BOOST_PP_CAT(Quantity, n));
BOOST_PP_REPEAT_FROM_TO(1, 4, LOOP_BODY, ~)
我不应对任何个人或职业声誉,骄傲,生命,肢体的损失负责;或使用上述代码导致的任何一种启示录的偶然事件。
答案 2 :(得分:0)
您应该使用数组来保存变量,如下所示:
int data[4] = {0};
for(unsigned int i = 0; i < 4; i++) {
printf("Enter the data for item #%d: ",i);
scanf("%d", &data[i]);
}