'Why is it not dividing correctly [closed]

Why is this code not dividing correctly?

This code is supposed to find the sum of all the numbers that can mod b(from 1 to a), and the numbers that couldn't. Then output the average value of the sums.

Code:

#include <iostream>
using namespace std;
int main(){
    int a,b;
    cin >> a >> b;
    double asum = 0, bsum = 0;
    double acnt = 0, bcnt = 0;
    double ansa = 0, ansb = 0;
    for(int i = 1; i<=a; i++){
        if(i%b == 0){
            asum+=i;
            acnt++;
        }else{
            bsum+=i;
            bcnt++;
        }
    }
    cout << asum << " " << acnt << endl;
    cout << bsum << " " << bcnt << endl;
    ansa = asum / acnt;
    ansb = bsum / bcnt;
    printf("%.1lf", &ansa);
    cout << " ";
    printf("%.1lf",&ansb);
    return 0;
}

Input:

100 16

The Output Now:

0.0 0.0

Correct Output

56.0 50.1

Does anyone know what's happening?



Solution 1:[1]

printf("%.1lf", &ansa);

%lf format specifier requires that the argument is of type double (passing float would be fine too since it will be converted). The type of &ansa is double* which is a different type. The behaviour of the program is undefined.

I recommend using std::cout. It's easier to not completely break your program while using it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1