C 输入不会添加到数组列表
C Input won't add to array list
2 个数组不会存储输入,每个索引号的增量始终为 0,如 printf 所述。
int main()
{
int ingredientsAmount;
double ingredientsPrice[10];
double ingredientsWeight[10];
scanf("%d", &ingredientsAmount);
for(int i = 0; i < ingredientsAmount; i++)
{
scanf("%lf", &ingredientsPrice[i]);
printf("Price stored at index %lf\n", i);
scanf("%lf", &ingredientsWeight[i]);
printf("Weight stored at index %lf\n", i);
}
return 0;
}
您对 int
类型的对象使用了不正确的转换说明符 %lf
。使用转换说明符 %d
。写
printf("Price stored at index %d\n", i);
和
printf("Weight stored at index %d\n", i);
或者您可能指的是以下内容
printf("Price stored at index %d is %f\n", i, ingredientsPrice[i]);
和
printf("Weight stored at index %d is %f\n", i, ingredientsWeight[i]);
注意for循环是不安全的,因为用户输入的变量ingredientsAmount
的值可以大于声明数组的大小
至少你应该写
if ( scanf("%d", &ingredientsAmount) != 1 || ingredientsAmount > 10 )
{
ingredientsAmount = 10;
}
2 个数组不会存储输入,每个索引号的增量始终为 0,如 printf 所述。
int main()
{
int ingredientsAmount;
double ingredientsPrice[10];
double ingredientsWeight[10];
scanf("%d", &ingredientsAmount);
for(int i = 0; i < ingredientsAmount; i++)
{
scanf("%lf", &ingredientsPrice[i]);
printf("Price stored at index %lf\n", i);
scanf("%lf", &ingredientsWeight[i]);
printf("Weight stored at index %lf\n", i);
}
return 0;
}
您对 int
类型的对象使用了不正确的转换说明符 %lf
。使用转换说明符 %d
。写
printf("Price stored at index %d\n", i);
和
printf("Weight stored at index %d\n", i);
或者您可能指的是以下内容
printf("Price stored at index %d is %f\n", i, ingredientsPrice[i]);
和
printf("Weight stored at index %d is %f\n", i, ingredientsWeight[i]);
注意for循环是不安全的,因为用户输入的变量ingredientsAmount
的值可以大于声明数组的大小
至少你应该写
if ( scanf("%d", &ingredientsAmount) != 1 || ingredientsAmount > 10 )
{
ingredientsAmount = 10;
}