链接到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);
}
}发布于 2018-08-26 19:53:24
我认为你必须在最后写出输出。
并使用"%d\n“代替"\n%d”
首先更改这些行并检查:
scanf("\n%d",&n);至
scanf("%d",&n);和
printf("%d\n", count); // instead of \n%d如果不起作用,则将结果保存到一个数组中,并将其打印到另一个"while“中
发布于 2018-08-27 00:25:28
避免在scanf中使用空格(空格、换行符)。请参阅有关此主题Using “\n” in scanf() in C的早期帖子
发布于 2018-08-27 05:59:30
作为如何避免转换的示例:(我还为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;}
https://stackoverflow.com/questions/52025896
复制相似问题