Home > Mobile >  I coded a program which finds out class attendance percentage but the output is always zero
I coded a program which finds out class attendance percentage but the output is always zero

Time:10-01

This is the code. I am a newbie so please help. I don't know why it's output is always zero.

#include <iostream>
using namespace std;

/*Prgram Coded To Find Attendance Percentage*/

int main()
{
   int class_held, class_attended;

   cout << "How Many Classes Were Held?" << endl;

   cin >> class_held;

   cout << "How Many Classes Did You Attend?" << endl;

   cin >> class_attended;

   int class_attended_percentage = (class_attended / class_held) * 100;

   cout << "Your Attendence Is " << class_attended_percentage << endl;

   return 0;
}

CodePudding user response:

Two integers divided will always result in an int, in your case in 0 and 0 * 100 = 0

You need to cast at least one of the integers into double or float before dividing (I casted both):

#include <iostream>
using namespace std;

/*Prgram Coded To Find Attendance Percentage*/

int main()
{
   int class_held, class_attended;

   cout << "How Many Classes Were Held?" << endl;

   cin >> class_held;

   cout << "How Many Classes Did You Attend?" << endl;

   cin >> class_attended;

   int class_attended_percentage = (static_cast<double>(class_attended) / static_cast<double>(class_held)) * 100;

   cout << "Your Attendence Is " << class_attended_percentage << endl;

   return 0;
}

CodePudding user response:

Dividing 2 integers always gives the answer in an integer, where the decimal part is truncated. Since class_held >= class_attended, your answer will be 0.

Cast one of the values, class_held or class_attended, as a double. Here's the code which will work correctly:

#include <iostream>
using namespace std;

/*Prgram Coded To Find Attendance Percentage*/

int main()
{
   int class_held, class_attended;

   cout << "How Many Classes Were Held?" << endl;

   cin >> class_held;

   cout << "How Many Classes Did You Attend?" << endl;

   cin >> class_attended;

   int class_attended_percentage = (class_attended / (double)class_held) * 100;

   cout << "Your Attendence Is " << class_attended_percentage << endl;

   return 0;
}

CodePudding user response:

Your class_attended and class_held are int types.

When you use an integer to operate with another one, the result will be floored. As you calculate the percentage, the result is definitely a floating-point number less than 1, which is floored to zero eventually.

To get a correct result.

  1. Define your variables as floating-point types:
float class_held, class_attended;
  1. Or cast to floating-point before your operations:
int class_attended_percentage = ((float)class_attended / (float)class_held) * 100;
  •  Tags:  
  • c
  • Related