簡體   English   中英

用循環求解數組中的方程

[英]Solving an equation in an array with loop

由N個整數組成的數組,有必要計算下一個方程:

у = х1 * (х1 + х2) * (х1 + х2 + х3) * ... * (x1 + ... + xN)

我有兩個問題:

  1. 有更好的方法來找到解y嗎?
  2. 如何生成除0外的隨機數?

碼:

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以外的隨機數?

arr[i] = rand() % 9 + 1; // rando number in range 1 .. 9

是否有更好的方法來找到解y?

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM