I have a c++ language beginner question.

Asked 2 years ago, Updated 2 years ago, 84 views

Even if you enter numbers that do not fall apart by dividing them into 10 and 4, the decimal point does not come out properly. How can I get a decimal point? ㅠ<

    int a,b,c;
    printf ("Please enter a number to calculate."\n");
    scanf("%d %d",&a,&b);
    printf ("plus = 1 minus = 2 multiplied = 3 divided = 4\n");
    scanf("%d",&c);
    if (c==1)
        printf("%.3f",(a+b)*1.0);
    else if (c==2)
        printf("%.3f",(a-b)*1.0);
    else if (c==3)
        printf("%.3f",(a*b)*1.0);
    else 
        printf("%.3f",(a/b)*1.0);
    return 0;

Below is the execution screen

c++ calculator

2022-09-20 15:07

1 Answers

The result of the operation between two integers is an integer.

Like (double)a/b, if you accidentally convert the value of a and divide it by b, it is a real number/integer, so the result is a real number.

Please refer to the code below.

#include <stdio.h>

int main()
{
    int a, b, c;
    printf ("Please enter a number to calculate."\n");
    scanf("%d %d", &a, &b);
    printf ("plus = 1 minus = 2 multiplied = 3 divided = 4\n");
    scanf("%d", &c);
    if (c == 1)
        printf("%.3f", (double)a + b);
    else if (c == 2)
        printf("%.3f", (double)a - b);
    else if (c == 3)
        printf("%.3f", (double)a * b);
    else
        printf("%.3f", (double)a / b);
    return 0;
}


2022-09-20 15:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.