【问题标题】:alphabet shift with while loops带有while循环的字母移位
【发布时间】:2014-03-21 19:08:06
【问题描述】:

我正在编写一个程序,该程序打印字母然后在一个字母上移动。它将执行 26 次,因此最终看起来像这样:

1abcdefghijklmnopqrstuvwxyz
2zabcdefghijklmnopqrstuvwxy
3zxabcdefghijklmnopqrstuvwx
4zxyabcdefghijklmnopqrstuvw

到目前为止,我有一个 while 循环可以处理任何字母并打印一行字母字符串,但我不知道如何将它用于一个函数。

这是我的一封信代码:

#include <stdio.h>
int main(void)
{
char a = 'a';
char h = 'h';
char z = 'z';
int start_p;
 char one = 'a';
int shift = 1;//some of these are used for later parts of my code
int end_p = 1;
int start = 0;
char two = 'a';
one = 'h';

 while(one <= z)
{
 printf("%c", one);
one = one + 1;
 }
one = ;
while(one >= a)
{
printf("%c", one);
one = one - 1;
}

return(0);
}

【问题讨论】:

  • 不应该是3yzabcdefghijklmnopqrstuvwx4xyzabcdefghijklmnopqrstuvw吗?如果不是,你说的转移是什么意思?

标签: c loops while-loop


【解决方案1】:

假设字母 'a''z' 实际上是连续的,你可以这样做:

#define NUMBER_OF_LETTERS 26

main() {
    int i;
    int shift = 5;

    for(i = 0; i < NUMBER_OF_LETTERS; i++) {
        printf("%c", (i + shift) % NUMBER_OF_LETTERS + 'a');
    }
    printf("\n");
}

模运算符将保证您始终使用0-25 + 'a' 范围内的字母。

【讨论】:

    【解决方案2】:

    使用函数。注意代码不包括任何检查start 字符是否有效的错误。

    #include <stdio.h>
    void printAlphabet(int start)
    {
        int one = start;
        int nLettersInAlphabet = 26;
        while (nLettersInAlphabet--)
        {
            printf("%c", one);
            if (one++ == 'z')
                one = 'a';
        }
        printf("\n");
    }
    
    int main(void)
    {
    printAlphabet('a');
    printAlphabet('z');
    printAlphabet('h');
    }
    

    【讨论】:

      【解决方案3】:

      这个怎么样:

      #include <stdio.h>
      
      void printAlphabet(int start) 
      {
          int p;
          char letter;
      
          for(p=0; p<26; p++){
              letter = 'a' + (((start + p) - 'a') % 26);
              printf("%c", letter);
          }
          printf("\n");
      }
      
      int main(int argc, char **argv)
      {
          int i, start;
      
          for(i=26; i>0 ; i--){
              start = i + 'a';
              printAlphabet(start); 
          }
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 2012-07-01
        • 2015-06-16
        • 1970-01-01
        • 2012-12-02
        • 1970-01-01
        • 2021-01-31
        相关资源
        最近更新 更多