简体   繁体   中英

Can anyone please tell me which code is better?

So these two codes are for a programming assignment. The purpose of the code is to prompt the user for a positive number and it will display the number of positive numbers entered, the maximum and minimum of the user inputs and also the average of the numbers. Please explain to me which is better of the two codes and in the first code is there something wrong of me not initializing the values for max and min? Thank you

1 #include <stdio.h>
2 
3 int main(){
4     int n, pos, max, min, sum;
5     float avg;
6     pos = 0;
7     sum = 0;
8     while(1){
9         printf("\nEnter a positive number: ");
10         scanf("%d", &n);
11         printf("\n");
12         if(n < 1){
13             printf("Not a positive number. Exiting!\n");
14             break;
15         }
16         max = n > max ? n : max;
17         min = n < min ? n : min;
18         pos++;
19         sum += n;
20         avg = (float) sum / n;
21         printf("The positive: %d\n", pos);
22         printf("Max: %d and Min: %d\n", max, min);
23         printf("The avg: %.2f\n", avg);
24     }
25 }

This is the second code which does the exact thing.

  1 #include <stdio.h>
  2 
  3 int main(){
  4     int n, pos, max, min, sum;
  5     float avg;
  6     printf("Please enter a positive integer: \n");
  7     scanf("%d", &n);
  8     if(n<=0){
  9         printf("The numbered entered is not positive or zero.\n");
 10         return 1;
 11     }
 12     max = n;
 13     min = n;
 14     pos = 0;
 15     sum = 0;
 16     while(n>0){
 17         max = n > max ? n : max;
 18         min = n < max ? n : min;
 19         pos++;
 20         sum += n;
 21         scanf("%d", &n);
 22     }
 23     avg = sum / (float) pos;
 24     printf("\tNumber of positive integers: %d \n", pos);
 25     printf("\tMaximum value: %d\n", max);
 26     printf("\tMinimum value: %d\n", min);
 27     printf("\tAverage value: %.2f\n", avg);
 28     return 0;
 29 }

When you use a while loop, you need a condition. I think the error is in the first code, for no condition in the while loop. Check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM