Division function returns int.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<iostream>

int add(int a, int b) {
    int sum;
    sum=a+b;
    return sum;
}

int sub(int a, int b) {
    int sub;
    sub=a-b;
    return sub;
}

int mul(int a, int b) {
    int mul;
    mul=a*b;
    return mul;
}

float div(int a, int b) {
    float div;
    if (b==0) {
        return 0;
    }
    else {
    div=a/b;
    return div;
    }
}
int main() {
    int num1, num2;
    char ope,cont;
    std::cout<<"*******************************************************************************\n"
             <<"***                                                                         ***\n"
             <<"***                  Calculator, by Shubham Chaudhary                       ***\n"
             <<"***                                                                         ***\n"
                <<"*******************************************************************************\n\n";
    std::cout<<"Input the Calculation you want to make. The numbers and Operation seperated by Space.Ex: (3 + 3), (4 * 5), (5 - 3), (6 / 2).\n\n"
             <<"Input: ";
    std::cin>>num1>>ope>>num2;
    switch(ope) {
        case '+' :
            std::cout<<"\n"<<num1<<'+'<<num2<<'='<<add(num1, num2);
            break;
        case '-' :
            std::cout<<"\n"<<num1<<'-'<<num2<<'='<<sub(num1, num2);
            break;
        case '*' :
            std::cout<<"\n"<<num1<<'*'<<num2<<'='<<mul(num1, num2);
            break;
        case '/' :
            if (div(num1, num2)==0) {
                std::cout<<"0 as Divsor not Allowed!";
                break;
            }
            else {
            std::cout<<"\n"<<num1<<'/'<<num2<<'='<<div(num1, num2);
            break;
            }
        default :
            std::cout<<"Unknown/Invalid Operation! Try Again!";
            break;
    }
    std::cout<<"\n\nDo you want to continue(y/n)?\n"
             <<"Input: ";
    std::cin>>cont;
    if (cont=='y' || cont=='Y') {
        std::cout<<"\n\n";
        main();
    }
    else
    return 0;
}


This runs fine but even after the division function is a float, it returns an integer( Ex: 52/7=7) How I correct that? Meanwhile, I made wrote the complete code myself! :)
When you do a/b as you do in the function, since a and b are ints it does integer division. Cast one of them to a float.
thanks!
Topic archived. No new replies allowed.