Jul 17, 2013 at 1:03am UTC
Hello,
I am fairly new to programming and need help with a code.
I need to create a code that can add a suffix to a number.
Example:
Enter a value: 1
That would be the 1st.
Test another value? Yes
Enter a value: 11
I'd have to say the 11th
NOTE* - I am not asking that you write the whole code for me but how would I get started on this?
Your help is appreciated.
Thank you
Jul 17, 2013 at 9:49am UTC
@ MheonYaE
You didn't take into account that 21 is called 21st, 22 22nd, 23 23rd, 31 31st etc.
This should work correctly for every number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
#include <cmath>
using namespace std;
int main(){
bool running = true ;
while (running){
int number, test, digits=0;
double grej;
cout << "Enter a number: " ; cin >> number;
test = number;
while (test>=1){
test/=10;
digits++;
}
test = number;
if (digits>2){
grej = floor(test/pow(10,digits-2));
test -= grej*pow(10,digits-2);
}
cout << number;
if ((number-3)%10==0 && test != 13)
cout << "rd" << endl;
else if ((number-2)%10==0 && test != 12)
cout << "nd" << endl;
else if ((number-1)%10==0 && test != 11)
cout << "st" << endl;
else
cout << "th" << endl;
cin.ignore();
cin.get();
}
}
Last edited on Jul 17, 2013 at 10:17am UTC
Jul 17, 2013 at 9:55am UTC
Ye, but he said it had to say: 11th, thats why I did it like I did it... I know its grammatically wrong but thats what he requested.
Jul 17, 2013 at 10:06am UTC
This maybe is a little bit off topic, but 11th isn't grammatically incorrect, however 21th or 131th is, at least that is what I was taught.
Last edited on Jul 17, 2013 at 10:06am UTC
Jul 17, 2013 at 10:58pm UTC
Thank you so much for replying!
MheonYaE: Yes, what you have provides a very good outline of what I was looking for.
Btw: To make things a bit clear, there is a pattern for suffixes (suffices?)
Here:
1 st 2 nd 3 rd 4th 5th ... 1 0th
1 1th 1 2th 1 3th 1 4th 15th ... 20th
21 st 22 nd 23 rd 24th 25th ... 30th
31 st 32 nd 33 rd 34th 35th ... 40th
...
101 st 102 nd 103 rd 104th 105th ... 1 10th
11 1th 11 2th 11 3th 11 4th 115th ... 120th
121 st 122 nd 123 rd 124th 125th ... 130th
...
201 st 202 nd 203 rd 204th 205th ... 21 0th
21 1th 21 2th 21 3th 21 4th 21 5th ... 220th
221 st 222 nd 223 rd 224th 225th ... 230th
I know it's a bit harder to view but that's the best way of displaying it.
It takes into account the last number and (in some cases) the second to last number.
After that it's just a matter of placing the 'st', 'nd', 'rd' and 'th' (for everything after).
Catch my drift?
Thanks for the help guys!