gpt4 book ai didi

c - 如何在 C 中将整数数组从 0 标准化为 10

转载 作者:行者123 更新时间:2023-11-30 15:32:32 25 4
gpt4 key购买 nike

我有一个整数数组,范围从某个最小值到某个最大值。我想重新调整它们,使最小值缩放到 0,最大值缩放到 10,中间数字线性缩放到 0 到 10 之间最接近的整数。

没有语法错误,但代码无法按预期工作。

int main()
{
int d,k,m;
int B[20];
int A[] = { -3, 200, -22, 4, 5, 300, 2, 5, 4, 5, -1, 2, 3, 4, 7, 4, 2, 0, 7, -3 };

int i = 0, j = 0;
int maxval = 0;
for (i=0; i<20; i++)
{
if (A[i] > maxval)
maxval = A[i];
}
int minval = maxval;
for (i=0; i<20; i++)
{
if (A[i] < minval)
minval=A[i];
}
d=(maxval-minval)/10;
printf("minval= %d\nmaxval= %d\nd=%d ", minval, maxval, d);



for (i=0; i<20; i++)
{ m=minval;
for(k=0;k<10;k++)
{
if(A[i]>m && A[i]<(m+d))
B[i]=k;

}
m+=d;

}

for (i=0; i<20; i++)
{
printf("%d ", A[i]);
}

return 0;
}

最佳答案

相信这是正确的,但自从我做这种整数数学以来已经有 20 多年了(在一台小型计算机上,整数数学是你拥有的唯一数学类型)。

#include <stdio.h>

int main()
{
/* Input data */
int A[] = {
-3, 200, -22, 4, 5, 300, 2, 5, 4, 5,
-1, 2, 3, 4, 7, 4, 2, 0, 7, -3
};
int target_min = 0;
int target_max = 10;

/* Working variables */
int nelems;
int i;
int source_min;
int source_max;
int source_scale;
int target_scale;
int zsrc;
int scaled;

nelems = sizeof(A) / sizeof(A[0]);

source_min = source_max = A[0];
for (i = 1; i < nelems; i++) {
if (A[i] < source_min)
source_min = A[i];
if (A[i] > source_max)
source_max = A[i];
}

if (source_min == source_max) {
printf("Cannot scale: all values are the same\n");
return -1;
}

source_scale = source_max - source_min;
target_scale = target_max - target_min;

/* The heart of the algorithm: scale everything.
First, translate to a source_scale starting at zero.
Second, scale to target_scale (also starting at zero).
Third, translate to desired target scale.

Scaling is done with integer math. Can round three ways; leave
the desired one uncommented.
*/

for (i = 0; i < nelems; i++) {
zsrc = A[i] - source_min;

// Round down
//scaled = zsrc * target_scale / source_scale;

// Round up
//scaled = (zsrc * target_scale + source_scale - 1) / source_scale;

// Round to nearest; if exactly halfway, rounds up
scaled = (zsrc * target_scale * 2 + source_scale) / source_scale / 2;

A[i] = scaled + target_min;
}

for (i = 0; i < nelems; i++) {
printf("%d ", A[i]);
}
printf("\n");

return 0;
}

关于c - 如何在 C 中将整数数组从 0 标准化为 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24215419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com