I only have a small issue with my code and that is if I type in something like
an apple
it will give me as outout 33 instead of 65, 65 (=> 1 14 1 16 16 12 5)
how can I fix that ?
static int alphaSum(string letter)
{
int sum = 0;
char c = letter[0];
for (int i = 0; i < letter.Length; i )
{
c = (char)letter[i];
sum = char.ToUpper(c) - 64;
}
return sum;
}
CodePudding user response:
Please try this one, you should add if condition for not letter character:
static int alphaSum(string letter)
{
int sum = 0;
char c = letter[0];
for (int i = 0; i < letter.Length; i )
{
c = (char)letter[i];
if(Convert.ToInt32(char.ToUpper(c))>= 64 && Convert.ToInt32(char.ToUpper(c))<=90)
{
sum = char.ToUpper(c) - 64;
}
}
return sum;
}
CodePudding user response:
Your bug is that you are counting an empty space that gives you -32. Try this
static int alphaSum(string letter)
{
letter=letter.ToUpper();
int sum = 0;
for (int i = 0; i < letter.Length; i )
{
var c = Convert.ToInt16(letter[i]);
if( c < 65 || c > 90 ) continue;
sum = c-64;
}
return sum;
}
sum
65