【发布时间】:2019-09-19 18:41:47
【问题描述】:
对于作业,我必须用 C 编写代码,打印大于平均值的数字。
我已经编写了一些代码,但是当我插入一个数字或具有相同数字的数字(如 555)时,它没有给我答案。在 555 --> 5 (和 8 -> 8, 77 -> 等)的情况下,它应该给出。
我写的代码是:
(我对我采取的每一步都发表了评论。)
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *v[]) {
/* imput: 1 number between 1 and 2.000.000.000 */
int n; /* stores the value */
int ext, ext2; /* stores a copy of the number */
int rem; /* stores the remainders */
int tot; /* stores the total of the digits */
int avg; /* stores the average of the digits */
int i; /* counts the amount of digits */
int big; /* stores the biggest and second biggest value */
scanf("%d", &n);
/* seperate digits and add them */
ext=n;
ext2=n;
tot=0;
big=0;
avg=0;
i=0;
while(ext!=0 && n<2000000000 && n>=1){
rem=ext%10;
tot=tot+rem;
ext=ext/10;
i++;
};
/* average value */
avg=tot/i;
/* find and print higher numbers */
while (ext2>0){
rem = ext2 % 10;
if (rem > avg){
big += rem;
};
ext2 = ext2 / 10;
}
if(n<100 && n>9){
printf("%d\n", big);
} else if(big==avg){
printf("%d\n", 0);
} else if(big>=avg){
printf("%d\n", big);
};
return 0;
}
希望有人可以帮助我!
【问题讨论】:
-
你可能会得到一些反对意见,因为它的格式看起来像是一个家庭作业转储。尝试将其浓缩为一个特定的问题。您已经从不起作用的测试用例中获得了良好的开端。
-
我会用
fgets读取输入,然后你的(ASCII)数字就在一个不错的数组中。
标签: c sum average variable-assignment