0

Here is the code I am having trouble with it seems to work logically but perhaps I am missing a small detail as it doesn't work for chars or ints. Whenever I run it I get weird output like all Fs or all As.

#include <iostream>
template<class T>
char gradeIt(T mark,T maxMark){
    T grade =(mark/maxMark)*100;
    if(grade > 79)
        return 'A';
    else if(grade<=79 && grade >= 69) {
        return 'B';
    }
    else if(grade<=69 && grade>59)
        return 'C';
    else if(grade>50 && grade <=59)
        return 'D';
    else 
        return 'F';
}   
template<>
char gradeIt<char>(char mark,char maxMark){
    return mark;

}

nobody
  • 19,814
  • 17
  • 56
  • 77
Nick Krause
  • 1
  • 1
  • 8
  • 2
    It looks like `mark/maxMark` is performing integer division, which will round to 0 every time. You should static_cast(mark)/maxMark – AndyG Apr 16 '15 at 03:57
  • I known that is there any way to make it work for floats and intergers – Nick Krause Apr 16 '15 at 03:58
  • Unrelated to your immediate problem, but read [this](http://www.gotw.ca/publications/mill17.htm) and then change that specialization to an overload. – Praetorian Apr 16 '15 at 04:01

3 Answers3

4

T grade =(mark/maxMark)*100;

When the template parameter T is int this is performing integer division. For example, 80 / 100 = 0.

You could instead do.

T grade = mark * 100 / maxMark;
James Adkison
  • 9,412
  • 2
  • 29
  • 43
1

It looks like

(mark/maxMark)*100

is performing integer division, which will round to 0 every time.

You should static_cast<double>(mark)/maxMark to first convert to floating point so you don't lose any digits after the decimal place.

AndyG
  • 39,700
  • 8
  • 109
  • 143
0

This isn't doing what you want for integers.

T grade =(mark/maxMark)*100;

In the case of integer division (int and char have the same behavior in this) maxMark is greater than mark then the result will just be 0.

For example

int x = 100;
int y = 5;
int z = y/x;
assert(z==0);
ZachSand
  • 143
  • 8