Home > Enterprise >  C Input won't add to array list
C Input won't add to array list

Time:11-20

The 2 arrays wont store input, the increment of each index number is always at 0 as printf states it.


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;
}

CodePudding user response:

You are using the incorrect conversion specifier %lf with an object of the type int. Use the conversion specifier %d. Write

printf("Price stored at index %d\n", i);

and

printf("Weight stored at index %d\n", i); 

Or maybe you mean the following

printf("Price stored at index %d is %f\n", i, ingredientsPrice[i]);

and

printf("Weight stored at index %d is %f\n", i, ingredientsWeight[i]); 

Pay attention to that the for loop is unsafe because the value of the variable ingredientsAmount entered by the user can be greater than the sizes of the declared arrays.

At least you should write

if ( scanf("%d", &ingredientsAmount) != 1 || ingredientsAmount > 10 )
{
   ingredientsAmount = 10;
}
  • Related