Percentage of two integers

I am trying to calculate the percentage of value a of a+b. I want to know how much percent a's are contained in a+b.
I tried to fix this problem in this way:
#include <iostream>

using namespace std;

int main()
{
int casos;
cin>>casos;
int a;
int b;
float output[casos];
int o;
int total[casos];
int div[casos];
int por[casos];
for(int n=0;n<casos;n++){
cin>>a;
cin>>b;

por[n]=100;
output[n]=(a/(a+b))*100;
}

for(int x=0;x<casos;x++){
cout<<output[x]<<endl;

}
return 0;
}

In this case, the input is formed by "casos", which is the number of times I want to input a and b and the array output for the output of each case.

The output is 0, so this program is wrong. I dont understand why...

Maybe someone see's the error?
a and b are integers. When you divide integers, it does integer division, meaning it truncates result.

Cast either the numerator or denominator to a float, first.
(a / static_cast<float>(a+b))*100.0;

______________________________________________

PS: Standard C++ does not support variable-length arrays (VLAs). So if it still isn't working, consider using a vector.
1
2
3
4
5
6
7
8
9
10
#include <vector>
// ...

int casos;
cin >> casos;
vector<float> output(casos);

// ...

output[n] = (a / static_cast<float>(a+b))*100.0;
Last edited on
Alternatively, you could multiply by 100 first. You'll still end up truncating the answer instead of rounding it off, but for some applications, this is acceptable:
(100*a / (a + b))

Also, you don't need to arrays at all. Just output the answers as you read them:
1
2
3
4
    for (int n = 0; n < casos; n++) {
        cin >> a >> b;
        cout << (100*a / (a + b));
    }
I don't know whether it is completely reliable but incorporating 1.0 or 1. somewhere in the calculation forces a decimal answer to 5 figures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    int a = 6;
    int b = 12;
    
    std::cout << a/(a+b) << '\n';
    std::cout << a/(1.0*(a+b)) << '\n';
    std::cout << 1.0*a/(a+b) << '\n';
    std::cout << a/(1.0*a+b) << '\n';
    
    return 0;
}



0
0.333333
0.333333
0.333333
Program ended with exit code: 0


Why 6 significant figures you might ask.

EDIT: 6 sf not 5 sf due to manual sf counting error

Last edited on
Why 6 significant figures you might ask.
It comes from the default cout.precision being set to 6 (i.e. six digits).
https://en.cppreference.com/w/cpp/io/ios_base/precision
[Although not necessarily 6 sig figs, tailing 0s will be truncated]

It can be relied on, it's specified by the standard 27.5.5.2 basic_ios constructors.
https://en.cppreference.com/w/cpp/io/basic_ios/init
[But, to be pedantic, the exact values of floating-point numbers should not be relied on to begin with]
Last edited on
Thank you, question settled.
Topic archived. No new replies allowed.