converting char to ascii value then mod doesnt give correct output

Sep 3, 2018 at 6:52pm
So im trying to subtract two ascii value by first converting the chars to its ascii and then mod but its not giving the correct ouput. I am not sure why. Thanks for any help

1
2
3
4
5
6
  int shift;
  char c = 'e';
  char s = 't';
  shift = (int(c) - int(s)) % 26;
  cout << shift << endl;


answer should be 11 not -15
Sep 3, 2018 at 6:58pm
'e' becomes 99, 't' becomes 116.

99 - 116 is -15.

-15 % 26 is the remainder from ( -15 / 26 ).

Which is -15.

In cpp, % is NOT the same as the mathematical modulus function. In C++, % is the "remainder from division" operator.

That said, if you want to subtract two ascii values, just do it:

1
2
3
4
5
6
#include <iostream>

int main()
{
  std::cout << 't' - 'e';
}



Last edited on Sep 3, 2018 at 7:01pm
Sep 3, 2018 at 7:03pm
oh ok thank you. Is there a way to use the mathematical mod function in c++?
Last edited on Sep 3, 2018 at 7:03pm
Sep 3, 2018 at 9:34pm
chang123 wrote:
Is there a way to use the mathematical mod function in c++?


1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int mod( int x, int m ) { return x >= 0 ? x % m : mod( x + m, m ); }

int main()
{
   cout << mod( 'e' - 't', 26 ) << '\n';
}
Last edited on Sep 4, 2018 at 7:26am
Topic archived. No new replies allowed.