我如何回答这个以及如何将其更改为正确的代码 [英] How do I answer this this and how to change it into right codes

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

问题描述

使用数组,提示用户输入在-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";
}

推荐答案

首先查看随机数生成代码:是否生成所需的数字范围?

简单地说:不。

您的代码生成0到48之间的数字,而不是-10到10之间的数值。 Rememebr,%是模数运算符:它返回除数的余数,因此x%10将始终返回低于10的值,即0到9(含)。



尝试将其更改为:

Start by looking at your random number generation code: does it generate numbers in the required range?
Simply put: no.
Your code generates numbers between 0 and 48 inclusive, not values between -10 and 10 inclusive. Rememebr, "%" is the modulus operator: it returns the remainder of a division, so x % 10 will always return values below 10, i.e. "0" to "9" inclusive.

Try changing it to something like:
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.


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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆