简体   繁体   English

我在用 c 语言找到 3 个数字的平均值时遇到问题

[英]i am facing issue finding average of 3 numbers in c language

i am giving my code down below i want to tell you that i am getting my answer correct at the end but while i am putting the value there is some strange numbers coming left to it and also when i want to put my first value i always have to put the value twice i am just a beginner in c language if you can help me it will be really great thanks for giving your time我在下面给出我的代码我想告诉你我最后得到的答案是正确的,但是当我输入值时,会留下一些奇怪的数字,而且当我想输入我的第一个值时,我总是如果你能帮助我,我只是一个 c 语言的初学者,这将非常感谢你给我的时间

  #include<stdio.h>

int main ()
{
int a;
int b;
int c;

printf("please enter 3 numbers ");

printf("Enter 1st Number %d ", a);
scanf("%d ", &a);

printf("Enter 2nd Number %d ",  b);
scanf("%d ", &b);

printf("Enter 3rd Number %d ", c);
scanf("%d ", &c);

printf("Now you can see average of the three numbers \n");

int d = a + b + c ;
int e = d/3;

printf("%d ", e);

return 0;

}

In your code, you are prompting the user for the entry of a number using the "printf()" function which is good.在您的代码中,您使用“printf()”函数提示用户输入一个数字,这很好。 However, there is no need to include the variable in the "printf()" statements as the values will be entered into your integer variables with the associated "scanf()" functions.但是,不需要在“printf()”语句中包含变量,因为这些值将通过相关的“scanf()”函数输入到整数变量中。

What is happening here is that when you defined your three integers (a, b, and c), you allocated memory space for those integer variables.这里发生的情况是,当您定义三个整数(a、b 和 c)时,您为这些整数变量分配了内存空间。 And since those variables are not initialized with a value, the contents of those integers will contain whatever data value happens to be left over in that integer's memory location.而且由于这些变量没有使用值初始化,因此这些整数的内容将包含恰好留在该整数的内存位置中的任何数据值。

Simply, what you can do is change your prompt statement from:简单地说,您可以做的是将您的提示语句从:

printf("Enter 1st Number %d ", a);
scanf("%d ", &a);

printf("Enter 2nd Number %d ",  b);
scanf("%d ", &b);

printf("Enter 3rd Number %d ", c);
scanf("%d ", &c);

to:至:

printf("Enter 1st Number: ");
scanf("%d", &a);

printf("Enter 2nd Number: ");
scanf("%d", &b);

printf("Enter 3rd Number: ");    
scanf("%d", &c);

You will notice that I removed the trailing space in the "scanf()" formatting character.您会注意到我删除了“scanf()”格式字符中的尾随空格。 That was producing extra spaces.那是产生额外的空间。

Hope that clarifies things.希望能澄清事情。

Regards.问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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