简体   繁体   中英

Subtracting in C adds and turns negative

I'm trying to make a simple calculator that asks how many numbers are needed (right now just for adding and subtracting) then collects those numbers for the user and does the corresponding math depending on what the user wants.

Here's my code:

            if (option == 1) {
                printf("ADDITION\n");
                printf("How many numbers do you need? ");
                scanf("%d", &n);
                printf("Enter %d numbers:\n", n);

                for(i=1; i<=n; i++){
                    scanf("%lf", &addNum);
                    sol = sol + addNum;
                }
                printf("Solution: %.2lf\n", sol);
            }
            if (option == 2) {
                printf("SUBTRACTION\n");
                printf("How many numbers do you need? ");
                scanf("%d", &n);
                printf("Enter %d numbers:\n", n);

                for(i=1; i<=n; i++){
                    scanf("%lf", &subNum);
                    sol = sol - subNum;
                }
                printf("Solution: %.2lf\n", sol);
            }

The addition works perfectly fine. The subtraction does not. I figured if adding is working, then replacing the + with an - would suffice but I guess not. The problem I'm having is, for example:

ADDITION 
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: 15.00

SUBTRACTION
How many numbers do you need? 2
Enter 2 numbers:
10
5
Solution: -15.00

Can someone help me understand how rather than subtracting, it's adding the numbers and going negative?

For subtraction (option 2) you have not assigned sol to be the value you wish to subtract from. In your code, you start subtracting from 0 straight away and therefore are left with a negative value.

A fix could be to say that for first number you want to subtract from, set it to be the value of sol .

for(i=1; i<=n; i++)
{
    scanf("%lf", &subNum);
    if(i == 1)
    {
        sol = subNum;
    }
    else
    {
        sol = sol - subNum;
    }
}

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