本文介绍了我如何回答这个以及如何将其更改为正确的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用数组,提示用户输入在-10到10范围内生成的随机数。有效输入为1-50。显示输入的所有负数,并计算并输出输入的所有负数的总和。此外,显示输入的所有正数,并计算并输出所有输入的正数的乘积。



我有什么试过:



Using arrays, prompt the user to input how many random number to generate in the range of -10 to 10. Valid input is from 1-50. Display all the negative numbers entered and compute and output the sum of all the negative numbers entered. Also, display all the positive numbers entered and compute and output the product of all the positive numbers entered.

What I have tried:

        do{
            cout<<"No. of random numbers (-10-10): "<<endl;
            cin>>howmany;
                if(howmany<1 || howmany >50)
                cout<<"INVALID INPUT"<<endl;
        }while (howmany<1 || howmany>50);

    cout<<endl<<endl
    <<"The "<<howmany<<" random numbers from 1-50 are :"<<endl;

srand(time(0));

    for (ctr=0,negativectr=0,positivectr=0; ctr<howmany;>     {
        randnum[ctr]= rand() % 50-1;
        cout<<randnum[ctr]<<"\t";

        if (randnum[ctr] % 2 ==0)
            {
                positive[positivectr]=randnum [ctr];
                positivectr++;
            }

        else
            {
                negative[negativectr]=randnum [ctr];
                negativectr--;
            }

{
    cout<<endl<<endl<<"There are "<<positivectr<<" positive numbers generated"<<endl;
for(ctr=0;ctr<positivectr;ctr++);>
}
    cout<<positive[ctr]<<"\t";
}

cout<<endl;

cout<<"There are "<<negativectr<<" negative numbers generated"<<endl;
for(ctr=0;ctr<negativectr;ctr++)>
{
    cout<<negative[ctr]<<"\t";
}

推荐答案

eachRandomNumber = (rand() % 21) - 10;



21就在那里它生成0到20之间的值,包括它减去10以将值偏移到你的范围-10到10.



然后使用调试器来计算出其他的情况。


The "21" is there so it generates values between 0 and 20 inclusive, then it subtracts 10 to offset the values into your range -10 to 10.

And then use the debugger to work out what else is going on.


这篇关于我如何回答这个以及如何将其更改为正确的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 04:46
查看更多