这段代码现在做了什么:我给出int值并计算它们之间的平均值。 我花了几个小时试图做到这一点:我尝试过它,以便计算双值之间的平均值。我尝试了所有的东西,但它总是失败或进入无限循环或不会编译。
问题:那么我应该如何修改我的代码以使其与双值/数字一起使用?
#include <stdio.h>
void main()
{
int Tau[10]={0,0,0,0,0,0,0,0,0,0};
int r, i = 0;
int m = 0;
int huku = 0;
do{
printf("Enter numbers: ");
scanf_s("%d", &i);
Tau[m]+=i;
huku++;
}while(i != 0);
r = (Tau[m]/(huku-1));
printf("The average of your numbers is; %d\n", r);
}
答案 0 :(得分:3)
你的代码中有一些问题,但基本上,整数除法不会给你双打。整数除以整数的结果是另一个整数,而不是double。如果你想要双打,你需要将分子或分母强制转换为double并将结果存储为double。
答案 1 :(得分:1)
欢迎使用数值分析1001。
整数数学:
2 / 3 = 0;
4 / 2 = 2;
5 / 2 = 2;
整数不做分数。
答案 2 :(得分:1)
答案 3 :(得分:1)
最简单的变化只涉及四行:
double Tau[10] = {0,0,0,0,0,0,0,0,0,0};
double r, i = 0;
scanf_s("%f", &i);
printf("The average of your numbers is; %f\n", r);
请注意,这并未解决编码问题;它所做的只是将代码更改为使用double
而不是int
来阅读和使用。
答案 4 :(得分:0)
double r = 0;
int i = 0;
r = ((double)Tau[m]/((double)huku-1));
printf("The average of your numbers is; %f\n", r);
答案 5 :(得分:0)
// Question is tagged for C++, but the code is in C.
// I will change your code a bit, because you had quite a few mistakes.
#include <stdio.h>
void main ()
{
int sum = 0; // sum of all numbers you entered, to find average you only need total sum and number of entries
int numOfEntries; // number of entries (numbers taken from input)
int inputNum; // variable where you will write numbers from input one by one
double average; // Not really needed, but it can help to simplify the problem to you.
printf("Enter numbers: ");
do
{
scanf_s("%d", &inputNum);
sum += inputNum;
numOfEntries++;
} while (inputNum != 0); // I understand you read numbers until you read value 0.
// int / int will give you rounded number, not the true average, so we need to convert one of the operands to a real number, in this case double
// double / int or int / double will give you a real number as result, which will have true average value, and that is why I converted sum to a real number
if (numOfEntries != 0)
average = (double)sum / numOfEntries;
else
average = 0;
printf("The average of your numbers is; %f\n", average); // Here I did it again - print double instead of int to get true value.
}
更改此内容会更容易:
....
double sum = 0;
...
average = sum / numOfEntries; // Here sum is already double, not int, so you don't need to change it manually.
...
现在,如果你想让它适用于double,唯一的区别是:
double sum = 0;
double inputNum;
scanf_s("%lf", &inputNum);
average = sum / numOfEntries;
所以,要整理故事 - 你可以通过键盘输入一个数字,这个变量保存所有输入数字的总和,这个变量计算你从键盘输入的数字的数量。输入数字直到输入0作为值,然后程序将退出循环。平均数的公式是所有除以数字的总和。对于整数,您必须将转换添加到实数或其他方式,否则您将无法获得准确的结果。
我希望我没有混淆你。 :d