简体   繁体   English

在C中使用fgets的乘法

[英]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. 我要求用户输入9位数字并乘以每个数字。 Lets say if user enters 123456789 then we will do this: 让我们说如果用户输入123456789,那么我们将这样做:

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! 我为什么得到100 204和60我虽然得到:2 8 18或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] . 首先,在C编程语言中,数组从0开始索引。因此,您需要将索引从[1][2][3]更改为[0][1][2]

Second, each digit in the input is an ASCII character . 其次,输入中的每个数字都是ASCII字符 So the character 2 is actually stored in your array as the number 50. That's why num[1] * 2 is 100. 因此字符2实际上存储在数组中作为数字50.这就是num[1] * 2为100的原因。

The easiest way to convert the digits to the numbers you expect is to subtract '0' from each digit. 将数字转换为您期望的数字的最简单方法是从每个数字中减去'0' 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. 当你从stdin读取时,你得到一个char数组。

So in your example with "123" 所以在你的例子中用“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. 所以你当然会得到100分,204分这些数字。

Also note that arrays start with 0, not with 1! 另请注意,数组以0开头,而不是1!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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