我的任务似乎不起作用,我不知道为什么。我对 C 真的很陌生,我似乎无法让它发挥作用。我的老师不是很好,所以我不知道如何处理指针余数或如何将商和余数添加到返回值中。我不知道如何解决这些问题。
这是我的任务:
这是我的代码。我已经知道这很糟糕:
#include <stdio.h>
int myDiv(int a, int b, int *remainder);
int myDiv(int a, int b) {
int quotient = a / b;
remainder = a % b;
int answer = quotient, remainder;
return (answer);
}
int main() {
printf(" %d %d\n", myDiv(10, 5));
return 0;
}
以下是错误:
question3.c:5:5: error: conflicting types for 'myDiv'
int myDiv(int a, int b) {
^~~~~
question3.c:3:5: note: previous declaration of 'myDiv' was here
int myDiv(int a, int b, int *remainder);
^~~~~
question3.c: In function 'myDiv':
question3.c:8:5: error: 'remainder' undeclared (first use in this function); did you mean 'rewind'?
remainder = a % b;
^~~~~~~~~
rewind
question3.c:8:5: note: each undeclared identifier is reported only once for each function it appears in
我很努力,但我做不到。我只是不擅长。任何帮助将不胜感激!
编辑: b = 0 时的检查似乎不起作用。这是更新的代码。
#include <stdio.h>
int myDiv(int a, int b, int *remainder) {
int quotient = a / b;
*remainder = a % b;
return (quotient);
}
int main() {
int theQuotient, theRemainder;
theQuotient = myDiv(10, 5, &theRemainder);
printf("%d %d\n", theQuotient, theRemainder);
theQuotient = myDiv(-9, 4, &theRemainder);
printf("%d %d\n", theQuotient, theRemainder);
theQuotient = myDiv(0, 12, &theRemainder);
printf("%d %d\n", theQuotient, theRemainder);
theQuotient = myDiv(17, 0, &theRemainder);
printf("%d %d\n", theQuotient, theRemainder);
if (theQuotient = 0) {
theQuotient, theRemainder = 0;
printf("%d %d\n", theQuotient, theRemainder);
}
return 0;
}
C 不允许您使用多个原型定义相同的函数。您只需要定义一个,它接受int *remainder
,并传递它。第三个参数用于传回额外的返回值,需要为它声明storage,并将该storage的地址传递给函数:
#include <stdio.h>
int myDiv(int a, int b, int *remainder) {
int quotient = a / b;
*remainder = a % b; // Store remainder to caller provided storage
return quotient; // Return quotient directly
}
int main() {
int quo, rem;
quo = myDiv(10, 5, &rem); // Pass address of rem so myDiv can fill it in
printf(" %d %d\n", quo, rem);
return 0;
}
int answer = quotient, remainder;
永远不会去工作;它正在尝试声明名为answer
(用 初始化quotient
)和remainder
(未初始化,但您应该将其作为参数接收)的变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句