简体   繁体   English

有人可以帮助我解决我的C ++代码

[英]someone can help me troubleshoot my c++ code

Hello i'm new in c++ and i want to convert my code from pascal to c++ so this is my try : 您好,我是c ++的新手,我想将我的代码从pascal转换为c ++,所以这是我的尝试:

void decomp(int x, int *t[], int *l){
int p = 2;
int l = 0;

do{
if (x % p == 0){
x = x / p;
t[l] = p;
l += 1;     
}
else { p += 1; }
} while (x != 1);

}

and this is the correct function is pascal if someone need it to understand : 如果有人需要它,这是正确的函数是pascal:

procedure decomp(x:integer; var t : tab; var l : integer);
var
p : integer;
begin
l : = 0;
p: = 2;
repeat
if (x mod p = 0) then
begin
x : = x div p;
l: = l + 1;
t[l]: = p;
end
else
p: = p + 1;
until(x = 1);
end;

the issue is the compiler give me an error message : t[l]=p under li have this error : expression must have integral or unscoped enum type and under = i have this error : a value of type int cannot be assigned to an entity of type int* 问题是编译器给我一条错误消息:li下的t [l] = p出现此错误:表达式必须具有整数或无范围的枚举类型,而under =我遇到此错误:无法将int类型的值分配给实体类型为int *

PS the function need to return an array and his size ( var t :tab ; var l :integer) PS该函数需要返回一个数组及其大小(var t:tab; var l:integer)

You're shadowing the parameter l with a local variable l . 你遮蔽参数l与局部变量l Replace the int l = 0; 替换int l = 0; with just *l = 0; *l = 0; . You'll have to dereference l wherever you use it. 无论在何处使用,都必须取消引用l

Better yet, pass l by reference instead of by a pointer. 更好的是,通过引用而不是指针传递l This will be more similar to var l: integer in the Pascal code. 这将更类似于Pascal代码中的var l: integer

void decomp(int x, int *t[], int &l)

Then you won't have to dereference l as a pointer everywhere. 这样,您就不必在所有地方都取消引用l作为指针。

Also, t is an array of pointers. 而且, t是一个指针数组。 You're trying to assign an integer to a pointer. 您正在尝试为指针分配一个整数。 I'm not certain how to solve this with the code you have. 我不确定如何用您拥有的代码解决这个问题。 Perhaps it doesn't need to be an array of pointers: 也许不需要是一个指针数组:

void decomp(int x, int t[], int &l)
{
    int p = 2;
    l = 0;

    do
    {
        if (x % p == 0)
        {
            x = x / p;
            t[l] = p;
            l += 1;
        }
        else
        {
            p += 1;
        }
    } while (x != 1);
}

This: 这个:

int *t[]

is array of pointers to int, you need arrays of int. 是一个指向int的指针数组,您需要一个int数组。 So when you try to assign t[l]=p you assigning int to int * hence the error. 因此,当您尝试分配t[l]=p时,您会将int分配给int *因此会出现错误。 and for l you need reference, not pointer, so you code could be like this: 对于l您需要引用而不是指针,因此您的代码可能像这样:

void decomp(int x, int t[], int &l){
    int p = 2;
    l = 0;

    do{
        if (x % p == 0){
           x /= p;
           t[l++] = p;
        }
        else { ++p; }
    } while (x != 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM