(sml) 我可以得到一些帮助来实现一个计算案例数量的函数吗?
(sml) Can I get some help implementing a function that counts the number of cases?
我可以得到一些帮助来实现一个计算案例数量的函数吗?
首先,很抱歉一遍又一遍地问你同样的问题。
我已经尝试实现该功能一个多星期了,但我没有掌握它的窍门。
这是我现在写的代码。
fun count (x,nil) = 0
| count(x,y::ys) =
if x=y*2 then 2
else if x=y*4 then 4
else if x=y*10 then 10
else if x=y*20 then 20
else if x=y*100 then 100
else count(x,ys);
我知道这是一个非常无知的代码。但是你回答的功能我都实践过,完全不懂怎么应用。
这是我想要在 c 中实现的代码。
int count(int n, int arr[]) {
int cnt = 0;
int num1 = arr[0];
int num2 = arr[1];
if ((n % num1) == 0) cnt++;
if ((n % num2) == 0) cnt++;
if (((n - num1) % arr[1])==0) cnt++;
return cnt;
}
int main() {
int n;
int arr[30];
int res = 0;
scanf("%d", &n);
scanf("%d %d", &arr[0], &arr[1]);
res = count(n, arr);
printf("%d", res);
}
如果我和c代码做同样的事情,我想实现数字功能。我能得到一些帮助吗?
我没有完全理解代码的意图,但一个可能有用的技巧:
在 C 中,如果您发现自己正在更新局部变量,那么在 SML 中,您通常可以通过重新绑定变量来完成同样的事情:
C:
int x = 0;
if (condition1) x++;
if (condition2) x++;
...
return x;
SML:
let
val x = 0
val x = if condition1 then x+1 else x
val x = if condition2 then x+1 else x
...
in
x
end
使用这个技巧应该很容易翻译您的 C 函数。剩下的交给你。
只有一件事需要注意。当您在 SML 中以这种方式编写代码时,您实际上根本没有更新局部变量。上面的 SML 代码等同于此,我们每次都创建一个新变量。只是用另一种风格写起来更方便一些。
let
val x0 = 0
val x1 = if condition1 then x0+1 else x0
val x2 = if condition2 then x1+1 else x1
...
in
x2
end
我可以得到一些帮助来实现一个计算案例数量的函数吗?
首先,很抱歉一遍又一遍地问你同样的问题。
我已经尝试实现该功能一个多星期了,但我没有掌握它的窍门。
这是我现在写的代码。
fun count (x,nil) = 0
| count(x,y::ys) =
if x=y*2 then 2
else if x=y*4 then 4
else if x=y*10 then 10
else if x=y*20 then 20
else if x=y*100 then 100
else count(x,ys);
我知道这是一个非常无知的代码。但是你回答的功能我都实践过,完全不懂怎么应用。
这是我想要在 c 中实现的代码。
int count(int n, int arr[]) {
int cnt = 0;
int num1 = arr[0];
int num2 = arr[1];
if ((n % num1) == 0) cnt++;
if ((n % num2) == 0) cnt++;
if (((n - num1) % arr[1])==0) cnt++;
return cnt;
}
int main() {
int n;
int arr[30];
int res = 0;
scanf("%d", &n);
scanf("%d %d", &arr[0], &arr[1]);
res = count(n, arr);
printf("%d", res);
}
如果我和c代码做同样的事情,我想实现数字功能。我能得到一些帮助吗?
我没有完全理解代码的意图,但一个可能有用的技巧:
在 C 中,如果您发现自己正在更新局部变量,那么在 SML 中,您通常可以通过重新绑定变量来完成同样的事情:
C:
int x = 0;
if (condition1) x++;
if (condition2) x++;
...
return x;
SML:
let
val x = 0
val x = if condition1 then x+1 else x
val x = if condition2 then x+1 else x
...
in
x
end
使用这个技巧应该很容易翻译您的 C 函数。剩下的交给你。
只有一件事需要注意。当您在 SML 中以这种方式编写代码时,您实际上根本没有更新局部变量。上面的 SML 代码等同于此,我们每次都创建一个新变量。只是用另一种风格写起来更方便一些。
let
val x0 = 0
val x1 = if condition1 then x0+1 else x0
val x2 = if condition2 then x1+1 else x1
...
in
x2
end