c语言简单递归算法。但是一直报错。把一个数全部用2次幂的形式表示。
解决时间 2021-03-02 21:48
- 提问者网友:wodetian
- 2021-03-01 21:52
#include
void try(int n,int r){
if(n==1){
printf("2(%d)",r);
}
else {
try(n/2,r+1);
if(n%2==1)
printf("+2(%d)",r);
}
}
void main(){
int n;
scanf("%d",&n);
if(n>=1){
try(n,0);
}
else printf("error");
}
最佳答案
- 五星知识达人网友:一袍清酒付
- 2021-03-01 22:13
1.你的逻辑是正确的,但是try这个函数在c/c++的lib库中已经存在,所以会一直报错,你需要将try这个函数定义成其他的名称才行;
2.如果你使用gcc编译的话,建议你将main写成int的;
全部回答
- 1楼网友:猎心人
- 2021-03-01 22:49
#include
#include
#include
#include
//创建矩阵,矩阵用一维数组存储
double *matcreate(unsigned int m, unsigned int n)
{
double *p = (double *)malloc(sizeof(double) * m * n);
if (p == null) printf("创建矩阵失败!\n");
return p;
}
//输入矩阵元素
void matinput(double *a, unsigned int m, unsigned int n)
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
scanf("%f ", &a[i * n + j]);
}
}
return;
}
//随机产生矩阵元素,均匀分布于[from to]
void matinitrand(double *a, unsigned int m, unsigned int n, double from, double to)
{
if (a == null || m <= 0 || n <= 0) return;
double x;
srand(time(null));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
x = (1.0 * rand() / rand_max) * (to - from) + from;
a[i * n + j] = x;
}
}
return;
}
//转置
void mattranspose(double *a, double *b, unsigned int m, unsigned int n)
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
b[j*n +i]=a[i * n + j] ;
}
}
}
//输出矩阵
void matprint(double *a, unsigned int m, unsigned int n)
{
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
printf("%8.4f ", a[i * n + j]);
}
putchar('\n');
}
return;
}
//矩阵乘法c=a*b
void matmul(double *a, double *b, double *c, unsigned int m, unsigned int n, unsigned int k)
{
if (a == null || b == null || c == null || m <= 0 || n <= 0 || k <= 0) return;
double x = 0.0f;
for (int i = 0; i < m; ++i)
{
for (int u = 0; u < k; ++u)
{
x = 0.0f;
for (int j = 0; j < n; ++j)
{
x += a[i * n + j] * b[j * k + u];
}
c[i * k + u] = x;
}
}
return;
}
//b=a^n, a:m*m阶矩阵
void matfac(double *a, double *b, unsigned int n, unsigned int m)
{
double *c = (double *)malloc(sizeof(double) * m * m); //保存临时结果
if (n > 1)
{
matfac(a, c, n - 1, m);
matmul(a, c, b, m, m, m);
}
else
memcpy(b, a, sizeof(double)*m * m);
// printf("%d:\n",n);
// matprint(b, m,m);
free(c); //回收内存
return ;
}
#define m 3
#define n 4
#define k n
int main(int argc, char const *argv[])
{
double *a, *b, *b1,*bt, *c;
a = matcreate(m, n);
b = matcreate(n, k);
b1 = matcreate(n, k);
bt = matcreate(k,n);
c = matcreate(m, k);
if (!a || !b || !b1 || !bt || !c) return -1;
matinitrand(a, m, n, 0.0f, 1.0f);
printf("a=\n");
matprint(a, m, n);
matinitrand(b, n, k, 0.0f, 1.0f);
printf("b=\n");
matprint(b, n, k);
mattranspose(b,bt,n,k);
printf("b'=\n");
matprint(bt, k,n);
matmul(a, b, c, m, n, k);
printf("c=a*b\n");
matprint(c, m, n);
matfac(b, b1, 4, n);
printf("b^4\n");
matprint(b1, n, k);
return 0;
}
我要举报
大家都在看
推荐资讯