简体   繁体   中英

Multiplication using fgets in C

I am trying to do some multiplication. I am asking users to enter 9 digits number and multiply each digit with. Lets say if user enters 123456789 then we will do this:

123456789
246824682

We will multiply user input with this code:

    #include <stdio.h>
    int main(void) {

        char num[10];
        int num1,num2,num3;

        printf("Enter your num: ");
        fgets(num,10,stdin);

        num1 = num[1] * 2;
        num2 = num[2] * 4;
        num3 = num[3] * 6;

        printf("%d %d %d", num1,num2,num3);



        return 0;
}

When I run this this is what I get:

admin@matrix:~/cwork> ./lab2
Enter your num: 123
100 204 60admin@matrix:~/cwork>

Why am I getting 100 204 and 60 I though I would get : 2 8 18 OR 2818!

First, in the C programming language, arrays are indexed starting at 0. So you need to change the indexes from [1] , [2] , [3] to [0] , [1] , [2] .

Second, each digit in the input is an ASCII character . So the character 2 is actually stored in your array as the number 50. That's why num[1] * 2 is 100.

The easiest way to convert the digits to the numbers you expect is to subtract '0' from each digit. Putting it all together, your code should look like this

num1 = (num[0] - '0') * 2;
num2 = (num[1] - '0') * 4;
num3 = (num[2] - '0') * 6;

When you read from stdin you get a char array.

So in your example with "123"

your array looks like this:

num[1] == '2' == 50 // 50 is the ascii code for '2'
num[2] == '3' == 51 // 51 is the ascii code for '3'

So of course you are getting 100, 204 for these numbers.

Also note that arrays start with 0, not with 1!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM