Mahmoud
Mahmoud

Reputation: 197

Unexpected multiplication results with integer values read by scanf

I am a beginner at C and I am trying to write a vector multiplication code. I read in an array and the scale. Then I multiply this scale with each element in the array.

for (i = 0 ; i < 5 ; i++) 
{
    scanf("%d", &numbers[i]);
}

puts("Please enter the scale:");
scanf("%d", s);

puts("The scaled vector is:");

for (j = 0 ; j < 5 ; j++) 
{
    int r = numbers[j] * s  ;
    printf("%d\n", r);
}

However, when I run this code I receive unexpected values with the following inputs:

1
2
3
4
5

Scale:

2

Output:

6130616
12261232
18391848
24522464
30653080

When I replace the s in here numbers[j] * s by 2, for example, it will return the expected output.

Upvotes: 1

Views: 265

Answers (1)

perreal
perreal

Reputation: 97938

Send a pointer to scanf, so that you can get the value:

puts ("Please enter the scale:");
scanf ("%d" , &s);

Upvotes: 6

Related Questions