我正在尝试创建一个从0.05开始并以2.5结束的数组。我希望min和max之间的值以0.245的增量增长。
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
最终输出应该是这样的:
[0.05, 0.0745, 0.99, 0.1235, 0.148 ... 2.5]
答案 0 :(得分:4)
使用ES6 / ES2015点差运算符,您可以这样做:
#include <iostream>
using namespace std;
bool checkPalindrome(char* text);
char* clearString(char* src);
int main()
{
char buffer[1000];
cin.getline(buffer, 1000);
cout << boolalpha << checkPalindrome(buffer) << endl;
return 0;
}
bool checkPalindrome(char* text)
{
char* newStr = clearString(text);
if (!newStr)
return false;
int newLen = strlen(newStr);
for (int i = 0; i < newLen / 2; i++) {
if (newStr[i] == newStr[newLen - i - 1])
continue;
else
return false;
}
//delete[] newStr;
return true;
}
char* clearString(char* src)
{
unsigned len = strlen(src);
unsigned counter = 0;
for (int i = 0; i < len; i++) {
if (src[i] == ' '||src[i] == '.'||src[i] == ','||src[i] == '!')
counter++;
}
unsigned newSize = len - counter + 1;
char* dest = new(nothrow) char[newSize];
if (!dest) {
cout << "not enoough memory\n";
return NULL;
}
int i, j;
for(i = j = 0; j < newSize; ++i, ++j) {
if(src[i]==' '||src[i]=='.'||src[i]==','||src[i]=='!'||src[i]=='?')
i++;
else
dest[j] = src[i];
}
dest[j] = '\0';
return dest;
}
如果您需要将数字四舍五入为x位数,则可以这样做:
let min = 0.05,
max = 2.5,
items = 100,
increments = ((max - min) / items);
let result = [...Array(items + 1)].map((x, y) => min + increments * y);
Here是代码的示例
答案 1 :(得分:2)
喜欢
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
for(var i=min; i<max;i=i+increments) {
arr.push(i);
}
arr.push(max);
console.log(arr);
答案 2 :(得分:1)
试试这个:
var min = 0.05;
var max = 2.5;
var increments = ((max - min) / 100);
var arr = [];
for (var i = min; i < max; i +=increments) {
arr.push(i);
}
arr.push(max);
答案 3 :(得分:1)
基本理念是:
for (var val=min; val<=max; val+=increments) {
arr.push(val);
}
请记住,浮点运算通常会出现舍入错误。要修复它们,您可能希望在每一步舍入值:
var val = min;
while (val <= max) {
arr.push(val);
val += increments;
val = Math.round(val*1000)/1000; // round with 3 decimals
}
答案 4 :(得分:1)
在某些情况下,如果只是在每次迭代时增加数字,则由于舍入错误可能会得到错误的结果。更正确的方法是:
var min = 0.05;
var max = 2.5;
var increments = (max - min) / 100;
var arr = [];
for (var i = 0; i <= 100; ++i)
arr.push(min + increments * i);
答案 5 :(得分:0)
你可以使用这个功能
function test(){
var min = 0.05;
var max = 2.5;
var increments = (max-min)/100;
var arr = [];
for(var min=0.05;min<=max;min=min+increments){
arr.push(min);
}
alert(arr);
}
答案 6 :(得分:0)
function GetArray(minValue, maxValue, step) {
var resArray = [];
if (!isNaN(minValue) || !isNaN(maxValue) || !isNaN(step)) {
for (var i = minValue; i <= maxValue; i=i+step)
{
resArray.push(i);
}
}
return resArray;
}