Home > Back-end >  the programme codes of language c about input and output are wrong,could somebody help me find the f
the programme codes of language c about input and output are wrong,could somebody help me find the f

Time:09-07

I have the following code in c

#include <stdio.h>

int main(void)
{
    int a, b, c, sum;
    double d, p;
    sum = a   b   c;
    printf("请输入三个整数:");
    scanf("%d %d %d", &a, &b, &c);
    d = sum / 3;
    printf("3个整数的平均值是:d=%.2f", d);
    p = a / sum * 100;
    printf(",第一个数占和的比例是:p=%4.2f%%", p);
}

It is about entering three integers from the keyboard, average them, and calculate the ratio of the first number to the sum of the three numbers. The output result retains 2 decimal places . I cannot find where is wrong.

CodePudding user response:

The two main issues are:

  1. You calculate sum with uninitialized values for a, b and c. Move that calculation to after a successful scanf() to ensure those variables are set.
  2. You probably want to do the calculations of d and p with double, rather than integer, precision. I make use of automatic type conversion via fractional constants. The other two options are to change the type of sum from an int to a double, or explicitly use a type cast (see answer by @FeihuLiu).

Minor issues:

  1. Original code was formatted poorly (since fixed by one of our friends :-).
  2. Optional for main() but it's a good idea to return an integer as your declaration said you would.
  3. (not fixed) If you don't use p or d for anything else, consider just eliminating them in favor of doing the calculation call to printf()
  4. It's generally a good idea to reduce the scope of variables so I moved those definitions to just before they are used.
#include <stdio.h>

int main(void) {
    printf("请输入三个整数:");
    int a, b, c;
    if (scanf("%d %d %d", &a, &b, &c) != 3) {
        // TBD: translate error message
        printf("scanf failed\n");
        return 1;
    }
    int sum = a   b   c;
    double d = sum / 3.0;
    printf("3个整数的平均值是:d=%.2f", );
    double p = 100.0 * a / sum;
    printf(",第一个数占和的比例是:p=%4.2f%%", p);
    return 0;
}

CodePudding user response:

Besides the sum problem, integer division will result in integer. You can use the following code:

#include <stdio.h>

int main(void) {
    int a, b, c, sum;
    double d, p;
    printf("请输入三个整数:");
    scanf("%d %d %d", &a, &b, &c);
    sum = a   b   c;
    d = (double) sum / 3;
    printf("3个整数的平均值是:d=%.2f", d);
    p = (double) a / sum * 100;
    printf(",第一个数占和的比例是:p=%4.2f%%", p);
}
  •  Tags:  
  • c
  • Related