根据方程组解,生成n个n元一次方程组

2024-01-09 13:40:30

为了生成一个方程组,今天搓了一个

利用增广矩阵进行操作

程序还有些问题,先存一下,一会儿修改

有时候生成的随机数会导致程序运行结果不对

#include <stdio.h>
#include<iostream> 
#include <stdlib.h>
#include <time.h>
#include <unistd.h> 
using namespace std; 
 
int matrix[16][17]={
	{1 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,2},
	{0 ,1 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,8},
	{0 ,0 ,1 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,3},
	{0 ,0 ,0 , 1, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,1},
	{0 ,0 ,0 , 0, 1, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,4},
	{0 ,0 ,0 , 0, 0, 1, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,0},
	{0 ,0 ,0 , 0, 0, 0, 1 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 0,3},
	{0 ,0 ,0 , 0, 0, 0, 0 ,1 , 0 , 0 , 0 , 0, 0, 0, 0, 0,1},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 1 , 0 , 0 , 0, 0, 0, 0, 0,2},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 1 , 0 , 0, 0, 0, 0, 0,15},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 1 , 0, 0, 0, 0, 0,11},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 1, 0, 0, 0, 0,5},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 1, 0, 0, 0,34},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 1, 0, 0,2334},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 1, 0,23},
	{0 ,0 ,0 , 0, 0, 0, 0 ,0 , 0 , 0 , 0 , 0, 0, 0, 0, 1,234}
};

void print(){
	for(int i=0;i<16;i++){
		for(int j=0;j<16;j++){
			printf("%d,",matrix[i][j]);
		}
		printf("%d",matrix[i][16]);
		printf("\n");
	}
	printf("\n");
}

void mul(int i){
	srand(time(NULL)+ (unsigned) sleep(1));
    int multiplier= rand() % 8 + 1;
    for(int j=0;j<17;j++){
    	matrix[i][j]=matrix[i][j]*multiplier;
	}
	print();
} 

void add(){
	int sum=24;
	while(sum--){
		srand(time(NULL));
    	int random1, random2;
    	do {
        	random1 = 1 + rand() % 16; // 生成1到16之间的随机数
        	sleep(1); // 等待1秒钟,生成不同的时间种子
        	random2 = 1 + rand() % 16;
    	} while (random1 == random2);
    	
    	for(int i=0;i<=16;i++){
    		matrix[random1][i]+= matrix[random2][i];
		}
		print();
	}
} 

void print_result(){
	bool first=true;
	for(int j=0;j<16;j++){
		first=true;
		for(int i=1;i<16;i++){
			if(matrix[j][i-1]!=0&&first){
				printf("v%d*%d",i,matrix[j][i-1]);
				first=false; 
			}
			else if(matrix[j][i-1]!=0)
				printf("+v%d*%d",i,matrix[j][i-1]); 
		} 
		if(matrix[j][15]!=0){
			printf("+v16*%d=%d\n",matrix[j][15],matrix[j][16]);
		}else{
			printf("=%d\n",matrix[j][16]);
		}
	}
} 

int main(){
	printf("开始进行乘法操作,增广矩阵的每一行乘一个随机数\n"); 
	for(int i=0;i<=16;i++){
		mul(i);
	}
	printf("乘法完毕\n\n"); 
	printf("对增广矩阵的任意两行相加,开始加法\n"); 
	add(); 
	printf("加法完毕,输出得到的方程组:\n");
	print_result();
	
}

文章来源:https://blog.csdn.net/m0_73644864/article/details/135477202
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。