我是C ++的新手,不确定如何改进此代码 [英] I’m new to C++ and unsure about how to improve this code

查看:72
本文介绍了我是C ++的新手,不确定如何改进此代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码的目的是获取100个节点的随机数,并将这些节点随机分布在500 * 500范围内...(X,Y)


我需要改进此代码以不随机地分布这些节点
例如(0,100),(0,200)……(0,500)…(1,100)…….(500,500)
我需要在每个(x,y)坐标中放置4个节点
谁能帮我吗?

The purpose of the following code is to get a random number of 100 nodes and to distribute these nodes randomly in range 500*500 …(X,Y)


I need to improve this code to distribute these node not in random way
For example the (0,100) ,(0,200)……(0,500)…(1,100)…….(500,500)
I need to put 4 nodes in each (x,y) coordinate
Can anyone help me?

#include<iostream>
#include <fstream>
#include<cmath>
using namespace std;

void main() 
{
	int first[100],secnd[100];
	for (int i=0; i<100 ;i++)
	{   
	    first[i]=rand()%500;  //random number from  to 499
	    secnd[i]=rand()%500;  //random number from  to 499
            cout<<first[i]<<" "<<secnd[i]<<endl;
	}
}

推荐答案

您的代码中没有任何真正的错误(前提是您需要均匀分配随机点).
如建议的那样,您可以使用struct的单个数组来存储点,例如
There is nothing really wrong in your code (provided you need uniform distribution of random points).
As suggested you might use a single array of structs for storing points, e.g.
struct Point
{
  int x,y;
};

Point point[100];
//...


我的理解您的问题:

您要用4个随机点填充大小为100x100的5x5连续2D单元.

解决方案:

每个单元格都将在X和Y上使用双循环(从100排除到0至500,步骤100)进行独立处理.

为每个单元格生成4个随机点,坐标的范围为100x100(即单元格大小).

您的100点由(X + x,Y + y)给出.
My understanding of your problem:

You want to fill 5x5 contiguous 2D cells of size 100x100 each with 4 random points.

The solution:

Every cell will be processed independently, using a double loop on X and Y (from 0 to 500 excluded, step 100).

For each cell, generate 4 random points with coordinates in the range 100x100 (i.e. the cell size).

Your 100 points are given by (X + x, Y + y).


如果只需要4个项目,那么创建500个元素数组就没有多大意义了.另外,您可以使用Windows POINT [,但这可能是数学而非编程.
If you only need 4 items then there is little point in creating a 500 element array. Also, you could use the Windows POINT[^] structure rather than a 2D array to define each node. I''m not sure what you mean by "distribute these node not in random way", but that is probably mathematics rather than programming.


这篇关于我是C ++的新手,不确定如何改进此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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