C语言单词重量不同

时间:2015-08-05 18:06:37

标签: c

在这个问题中你应该阅读一组单词。每个单词仅由a-z和A-Z范围内的字母组成。每个字母都有一个特定的值,字母a值1,字母b值2,依此类推,直到字母z值26.

编写一个程序来计算每个测试用例的单词重量。 单词的权重是通过添加单词distinct字母的值来计算的。

#include <stdio.h> 
#include <stdlib.h> 
int wordDist(char letter){ 
    int count; 
    char str [200]; 
    int i; 
    char letters [26] = {'a','b','c','d','e','f','g','h','i',
                    'j','k','l','m','n','o','p','q','r','s','t'‌​,
                    'u','v', 'w','x','y','z'}; 
    for(i=0; i<26; i++){ 
        if(letter = letters[i]) 
            return i+1; 
    }
} 
int main() {
    int T, n, t; 
    scanf("%d", &T); 
    for(t = 1; t <= T; t++){ //count = 0;   
        //printf("%d\n",wordDist(str));
    } return 0;
}

2 个答案:

答案 0 :(得分:0)

ASCII字符只是连续的8位值,即'a'= 97,'b'= 98,'A'= 65,'B'= 66。

因此,要获得字母的“权重”,您只需计算小写字母减去'a'+ 1或大写字母减去'A'+ 1。

所以在伪代码中(因为我不打算为你写作业:

function char_weight(c):
    weight = c - 'A'
    if c greater than or equal to 'a':
        weight = weight + 'a' - 'A'
    return weight

function word_weight(word):
   add char_weight(each_char) to total
   return total 

答案 1 :(得分:0)

假设单词用一个空格分隔,代码看起来像这样:

c=fgetc(stdin);
while(c!=EOF) {
    s=0;
    while(c!=' ') { //while we are in a word
           if(c>='a' && c<='z')
               s+=(c-'a'+1);
           else
               s+=(c-'A'+1);
           c=fgetc(stdin);
    }
    printf("%d\n", s);
}

由于ASCII码,此s+=(c-'a'+1);是可能的。在ASCII(美国信息交换标准码)中,每个字符都有一个值:&#39; a&#39; = 97 。这意味着您不必编写s+=(c-97+1)(也可以使用),但您不必记住任何字符的ASCII代码。

要说服自己,请写下以下内容:

if('b' == 98)
    printf("They are equal);
else
    printf("They aren't equal");

证明您可以为角色添加数字:

char ch;
ch='a';
ch=ch+1;
if(c == 'b')
  printf( "you can add a number to a character" );