[英]Taking the average of the 3 numbers in the array with the pointer
int main()
{
float dizi[10], *ptr, ort, toplam = 0.0;
int i;
ptr = dizi;
for (i = 1; i <= 3; i++)
{
printf("input %d. value : ", i);
scanf("%f", &*ptr);
toplam += *ptr;
}
for (i = 4; i <= 10; i++)
{
*(ptr + i) = toplam / 3;
printf("%d. value is : %f\n", i, *(ptr + i));
}
}
The procedure is as follows: For example, the first three values I entered are 2,3,4 and the average of them, '3', is shown as the 4th element of the array.过程如下:例如,我输入的前三个值是 2、3、4,它们的平均值“3”显示为数组的第 4 个元素。 After that, it should take the average of the 2nd, 3rd and 4th values of the array, '3','4','4', and save the number 3.66 as the 5th value of the array.
之后,它应该取数组的第 2、3 和第 4 个值 '3'、'4'、'4' 的平均值,并将数字 3.66 保存为数组的第 5 个值。 This process should continue until the last element of the array, the 10th value.
这个过程应该一直持续到数组的最后一个元素,第 10 个值。 In short, each element must be calculated as the average of the previous three element values and added to the array sequentially.
简而言之,每个元素必须计算为前三个元素值的平均值,并按顺序添加到数组中。 I need to solve this using pointer.
我需要使用指针来解决这个问题。
There are multiple problems in your code:您的代码中有多个问题:
Here is a modified version:这是修改后的版本:
#include <stdio.h>
int main() {
float dizi[10], *ptr = dizi, sum = 0.0;
int i;
for (i = 1; i <= 3; i++) {
printf("input %d. value: ", i);
if (scanf("%f", ptr) != 1)
return 1;
sum += *ptr;
ptr++;
}
for (i = 4; i <= 10; i++) {
*ptr = sum / 3; // store the average
printf("%d. value is: %g\n", i, *ptr);
sum -= ptr[-3]; // subtract the first value
sum += *ptr; // add the next value
ptr++;
}
return 0;
}
Sample run:样品运行:
input 1. value: 2
input 2. value: 3
input 3. value: 4
4. value is: 3
5. value is: 3.33333
6. value is: 3.44444
7. value is: 3.25926
8. value is: 3.34568
9. value is: 3.34979
10. value is: 3.31824
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.