【问题标题】:Could someone explain why my last else statement will not run?有人可以解释为什么我的最后一个 else 语句不会运行吗?
【发布时间】:2020-11-19 02:40:03
【问题描述】:

我正在尝试将我的 argv 字符串转换为整数。对于某些人来说,我无法让我的最后一个 else 语句运行。任何帮助将不胜感激。我只是从 C 开始。这是我的代码。

#include <cs50.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int main(int argc, string argv[])
{
    if (argc == 2)
    {
        for(int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            if (!isdigit(argv[1][i])) {
            printf("Usage: ./caesar key\n");
            
            }
            
        }
    }
        else if (argc != 2)
        {
            printf("Usage: ./caesar key\n");
        }
        
        else if (argc == 2)
        {
            int x = atoi(argv[1]);
            printf("%i", x);
            return 0;
        }
}

【问题讨论】:

    标签: c if-statement cs50 argv atoi


    【解决方案1】:

    用大括号和缩进写的,你的代码结构是这样的:

    if ( argc == 2 )
    {
         stuff
    }
    else
    {
        if ( argc != 2 )
        {
             stuff
        }
        else if ( argc == 2 )
        {
             stuff
        }
    }
    

    所以一旦第一次测试失败,执行跳转到对应的else控制的块结束之后。

    您编写的代码具有相同的逻辑,只是省略了可选的大括号和不同的空格。

    【讨论】:

      【解决方案2】:

      我的最后一个 else 语句无法运行。
      ...为什么我的最后一个 else 语句不会运行?

      使用更好的格式,可能更容易看到代码在同一个 if, else if, else if 树中测试了两次 (argc == 2)。

      int main(int argc, string argv[]) {
        if (argc == 2) {
          for (int i = 0, n = strlen(argv[1]); i < n; i++) {
            if (!isdigit(argv[1][i])) {
              printf("Usage: ./caesar key\n");
      
            }
      
          }
        } else if (argc != 2) {
          printf("Usage: ./caesar key\n");
        } else if (argc == 2) {  // cannot be true given prior `if (argc == 2)`
          int x = atoi(argv[1]);
          printf("%i", x);
          return 0;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-08-31
        • 1970-01-01
        • 2017-12-12
        • 2012-06-15
        • 2015-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多