1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
I Y S Z
  • 45
  • 5

1 Answers1

1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • I've learned from a source that using `scanf` is unsafe due to the reason that it can be used to overload a buffer. But i don't mind that rn cuz I just use what I've learned so far on EDX. And cant i use `scanf(10%d)` to get a cap of input? like 1 2 3 4 5 6 7 8 9 10 and more then 10 would be ignored? – I Y S Z Nov 19 '21 at 21:18
  • @IYSZ No you can not do this way. In this case you need to use 10 conversion specifiers and corresponding arguments like (for 3 numbers) scanf( "%d %d %d", &x, &y, &z ); – Vlad from Moscow Nov 19 '21 at 21:23
  • okey I will respond if it works for me. So far the `printf` is fixed :) so silly me haha – I Y S Z Nov 19 '21 at 21:25
  • Btw, what do you mean with the last codeblock which is about the if statement to check if `ingredientsAmount` is not equal to 1 or bigger then 10? And why should then `ingredientsAmount` be = 10? wont it just override the input? Or is it just a "safeway" to override `ingredientsAmount` input if its greater then 10 like 11 100 12? – I Y S Z Nov 19 '21 at 21:32
  • @IYSZ 1 is the return value of scanf that says that input was successful. The user can enter for example a letter instead of a digit or enter a value greater than 10. – Vlad from Moscow Nov 19 '21 at 21:35
  • Okey that was not my intention actually. "make sure that users cannot enter a number of ingredients greater than 10." < this is my goal and it works with `scanf(10%d)` as 10 is the max range the user can put in from 1 - 10 – I Y S Z Nov 19 '21 at 21:47