0

I seem to stuck in a extremely simple question, but I cannot fix it and understand why. Below is my code:

#include <stdio.h>
#define SIZE 8

int main(void){
  int i, j;
  double nums[SIZE];
  double input;
  
  printf("Enter 8 doubles: ");
  for (i = 0; i < SIZE; i++){
    nums[i] = scanf("%lf", &input);
  }

  for (i = 0; i < SIZE; i++){
    printf("%lf ", nums[i]);
  }

  return 0;
}

Below is the result I got:

Enter 8 doubles: 1 2 3 4 5 6 7 8
1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000

What is the main problem about my code? Thank you!

2
  • 2
    scanf returns the number of items scanned. You want to assign input to your array items. Commented Oct 18, 2020 at 7:28
  • Oh Yeah! I forgot that... I am too stupid to notice that.. Commented Oct 18, 2020 at 12:11

2 Answers 2

1

Try this one and you should read the data in variable with scanf because return from scanf is the number of items of the argument list successfully read:

 #include <stdio.h>
 #define SIZE 3

 int main(void){
   int i, j;
   double nums[SIZE];
   double input;

   printf("Enter 8 doubles: ");
   for (i = 0; i < SIZE; i++){
     scanf("%lf", &input);
     nums[i] = input;// or scanf("%lf", &num[i]); 
   }

   for (i = 0; i < SIZE; i++){
     printf("%lf ", nums[i]);
   }

   return 0;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

@Jabou Please let me know if this answer works for you.
0

scanf return number of elements scanned.

i think you meant:

for (i = 0; i < SIZE; i++){
    scanf("%lf", &nums[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.