【问题标题】:cs50 sandbox for-loop issuecs50沙箱for循环问题
【发布时间】:2020-12-11 05:31:40
【问题描述】:

我想制作一个程序,当我给它一个数字时,它会从它向下计数。

这是我的代码:

#include <stdio.h>
#include <cs50.h>
 
int main(void) {
    int i = get_char("Choose a number.\n");
    for (int a = 0; a < i; a++) {
         printf("a\n");
    }
}

【问题讨论】:

  • 问题出在哪里?
  • printf("%d\n", a);
  • 问题是它只是说 a a a a a a a a a a。
  • @El_Moroccan 为什么你使用 get_char 而不是 get_int?
  • @JohnnyMopp 他应该很高兴他的系统不使用字符 6 的值为 246 的 EBCDIC 编码。:)

标签: c for-loop get char cs50


【解决方案1】:

一些事情:

  1. 你是printfing "a",而不是变量 a 的值。试试:

    print("%d\n", a);
    
  2. 你没有从i倒数到1;你从 0 数到 i-1。你想要更多类似的东西:

    for (int a = i; a >= 1; a--)
    

    (如果你想倒数到 0,显然,将 1 改为 0。)

  3. 你正在读取一个字符,但你想读取一个整数:

    int i = get_int("Choose a number.\n");
    
  4. 而且您没有从应该返回 int 的函数中返回任何内容。

        return 0;
    }
    

【讨论】:

  • 有一个错字 print("$d\n", a);必须是 %d 而不是 $d。
  • 重新阅读 cmets。这对你很有用。
  • 两件事:或者四件事?
  • 如果您使用的是 C99 或更高版本,您可以在 main 函数中省略 return 0;
  • OTOH,即使您可以省略 return 0;,IMNSHO 仍然最好从 main() 显式返回一个值,即使在末尾也是如此。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 2018-11-05
  • 1970-01-01
  • 2014-03-19
  • 2020-09-15
相关资源
最近更新 更多