“N”个整数数组,有必要计算下一个等式:
у = х1 * (х1 + х2) * (х1 + х2 + х3) * ... * (x1 + ... + xN)
我有两个问题:
y
?代码:
srand(time(NULL));
const int size = 10;
int arr[size];
int pro=1;
for (int i = 0; i < size; i++)
{
arr[i] = rand() % 10;
}
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
for (int i = 0; i < size; i++)
{
int sum = 0;
for (int j = 0; j <= i; j++)
{
sum = arr[j];
}
pro *= sum;
}
cout << pro << endl;
答案 0 :(得分:1)
如何生成0以外的随机数?
arr[i] = rand() % 9 + 1; // rando number in range 1 .. 9
有没有更好的方法来找到解决方案?
long pro = 1;
long sum = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i]; // i==0: x1, i==1: x1+x2, i==3: x1+x2+x3, ....
pro *= sum;
}
这应该是你的代码:
srand(time(NULL));
const int size = 10;
int arr[size];
for (int i = 0; i < size; i++)
arr[i] = rand() % 9 + 1;
for (int i = 0; i < size; i++)
cout << arr[i] << ' ';
cout << endl;
long pro = 1;
long sum = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
pro *= sum;
}
cout << pro << endl;