1. 四舍五入
float val = 0.9;
int nval = val + 0.5;
2. 浮点类型的数组
int quantization(float * pnote, int note_num, int * out_template)
{
float best_shift = -1000.0f;
float min_dist = 10000.0f; // 最小路径
// 寻找最小路径(最佳偏移值)
// 把1一百等分,精度为0.01
for (int i = -50; i < 50; ++i)
{
float cur_shift = i * 0.01;
float cur_dist = 0.0f;
for (int j = 0; j < note_num; ++j)
{
if (pnote[j] < 1.0f)
continue;
cur_dist += fabs((pnote[j] + cur_shift) - int(pnote[j] + cur_shift + 0.5)); // 量化公式
}
if (cur_dist < min_dist)
{
min_dist = cur_dist;
best_shift = cur_dist;
}
}
// 量化
for (int i = 0; i < note_num; ++i)
{
if (pnote[i] > 1.0f)
{
pnote[i] = int(pnote[i] + best_shift + 0.5);
}
}
return 0;
}