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...
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));
}
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]