【问题标题】:Print the occurences of digit 4. - CodeChef打印数字 4 的出现次数。 - CodeChef
【发布时间】:2018-08-26 11:43:26
【问题描述】:

链接到Problem - LuckyFour

代码在我自己的系统上运行良好,但提交时显示错误答案?

#include <stdio.h>
void main()
{
    int t, n, count;
    scanf("%d", &t);
    while(t--)
    {
        count=0;
        scanf("\n%d",&n);
        while(n>0)
        {
            if(n%10==4)
            {
                count++;
            }
            n=n/10;
        }
        printf("\n%d", count);
    }
}

【问题讨论】:

  • const auto str = std::to_string(t); std::cout &lt;&lt; std::count(str.begin(), str.end(), '4') &lt;&lt; '\n';
  • int main(void) { /* ... */ return 0; }
  • 请不要标记多种语言,只使用与您真正编程的语言相对应的标记。
  • 建议:使用'\n' 终止行。 printf("\n%d", 42); 不像 printf("%d\n", 42); 那样平常。
  • 为什么不使用 getline 直接计算 '4' 字符呢?无需转换。您还假设您正在从标准输入读取。这是给的吗?您链接到的描述中没有明确说明。

标签: c


【解决方案1】:

我认为你必须在最后写输出。

并且还使用“%d\n”而不是“\n%d”

首先更改这些行并检查:

scanf("\n%d",&n);

scanf("%d",&n);

printf("%d\n", count); // instead of \n%d

如果不工作,将结果保存在一个数组中并在另一个“while”中打印它们

【讨论】:

  • 成功了。通过更改int main(void) 并添加return 0; 另外,有了这个printf("%d\n", count); 你能告诉我到底出了什么问题吗?
  • 主要问题可能是您的输出没有以换行符结尾。打印行,使它们以换行符结尾;只有在需要空行时才在前面添加换行符。
【解决方案2】:

避免在 scanf 中使用空格(空格、换行符)。请参阅有关此主题的早期帖子Using “\n” in scanf() in C

【讨论】:

    【解决方案3】:

    作为我如何避免转换的示例: (还添加了一些错误检查和main 的实际返回值,我喜欢拥有,类 Unix 操作系统也是如此......)

    #include <stdio.h>
    #include <stdlib.h>
    
    static size_t count_char_in_line(const char *l, size_t len, char c){
        size_t res=0;
        while(len>0){ 
            if (*(l++) == c) res++; 
            len--;
        }
        return res;
    }
    
    int main(void){
    
    size_t nr_of_expected_lines=0;
    ssize_t nr_read;
    size_t line_length;
    char *line = NULL;
    int ret=0;
    
    if (-1 != ( nr_read = getline(&line, &line_length, stdin))){
        if (1 != sscanf(line, "%zu", &nr_of_expected_lines)){
            fprintf(stderr, "not a number on the first line..\n");
            ret=1;
            goto cleanup;
        }
    } else {
        fprintf(stderr, "premature end of stdin..\n");
        ret=2;
        goto cleanup;
    }
    while (nr_of_expected_lines > 0 && (-1 != (nr_read = getline(&line, &line_length,stdin)))){
        if (nr_read > 1){
            size_t count=count_char_in_line(line, nr_read-1, '4');
            fprintf(stdout, "%zu\n", count);
            nr_of_expected_lines--;
        } else {
            fprintf(stderr, "empty line error\n");
            ret= 3;
            break;
        }
    }  
    
    cleanup:
    free(line);
    return ret;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-09
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多