C ++多个随机数加起来等于一定数 [英] C++ multiple random numbers adding up to equal a certain number

查看:125
本文介绍了C ++多个随机数加起来等于一定数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个麻烦的计算这一个,我有一堆int变量,从1-9生成随机数。我需要他们生成正确的数字等于一个特定的数字,例如30。

Having a little trouble figuring this one out, I have a bunch of int variables which are generating random numbers from 1-9. I need them to generate the correct numbers to equal to a certain number, for example 30.

int numone = rand()%10;
int numtwo = rand()%10;
int numthree = rand()%10;
int numfour = rand()%10;
int finalsum;

do{
finalsum = numone + numtwo + numthree + numfour;
}while(finalsum !=30);

我不知道我是否正确的方法,但当我尝试编译上述代码,我甚至不会得到一个数字,有时我得到一个时间限制超过的错误,也许它花了太长时间。有没有另一种方式,我可以做到这一点?

I am not sure if I am going about this the right way but when I try to compile the above code, I don't even get a number and sometimes I get a "Time limit exceeded" error, perhaps it is taking too long. Is there another way I can do this?

推荐答案

好吧,我希望你意识到在你的while循环中,你实际上并不改变随机数的值。你所做的是基本上检查 finalsum = numone + numtwo + numthree + numfour; 相同的条件如果不等于30.你应该做的是:

Well, i hope you realize that in your do while loop, you are not actually changing the values of the random numbers.What you are doing is basically checking the same condition of finalsum = numone + numtwo + numthree + numfour; infinitely if it does not equal 30.What you should do is:

int numone,numtwo,numthree,numfour,finalsum;
do{
numone=rand()%10;
numtwo=rand()%10;
numthree=rand()%10;
numfour=rand()%10;
finalsum = numone + numtwo + numthree + numfour;
}while(finalsum !=30);

这篇关于C ++多个随机数加起来等于一定数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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