✨博文作者:烟雨孤舟
喜欢的可以 点赞 收藏 关注哦~~✍️ 作者简介: 一个热爱大数据的学习者
输入两个正整数m和n,求从m加到n的和(m <= n),并输出,请选出正确答案。
#include
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void sum(int a, int b, int t) {
int i;
t = a;
for (i = a+1; i <= b; ++i) {
t += i;
}
}
int main(int argc, char** argv) {
int m, n, total = 0;
printf("请输入两个整数:");
scanf("%d,%d", &m, &n);
if (m > n)
swap(&m, &n);
sum(m, n, total);
printf("a = %d, b = %d\n", m, n);
printf("total = %d\n", total);
return 0;
}
//错误,void sum(int a, int b, int t) 没有返回值
#include
int sum(int, int, int);
void swap(int*, int*, int*);
int main(int argc, char** argv) {
int m, n, total;
printf("请输入两个整数:");
scanf("%d,%d", &m, &n);
if (m > n)
swap(&m, &n);
total = sum(m, n);
printf("a = %d, b = %d\n", m, n);
printf("total = %d\n", total);
return 0;
}
int sum(int a, int b) {
int i;
for (i = a+1; i <= b; ++i) {
a += i;
}
return a;
}
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
//错误,函数定义和函数声明参数列表的数量应相同
#include
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int sum(int a, int b) {
int i;
for (i = a+1; i <= b; ++i) {
a += i;
}
return a;
}
int main(int argc, char** argv) {
int m, n, total;
printf("请输入两个整数:");
scanf("%d,%d", &m, &n);
if (m > n)
swap(&m, &n);
total = sum(m, n);
printf("a = %d, b = %d\n", m, n);
printf("total = %d\n", total);
return 0;
}
//正确
#include
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int sum(int a, int b) {
int i;
for (i = a+1; i <= b; ++i) {
a += i;
}
return a;
}
int main(int argc, char** argv) {
int m, n, total;
printf("请输入两个整数:");
scanf("%d,%d", &m, &n);
if (m > n)
swap(m, n);
total = sum(n, m);
printf("a = %d, b = %d\n", m, n);
printf("total = %d\n", total);
return 0;
}
//错误, total = sum(n, m);参数顺序与实参顺序不一致。
解析:本题考察了函数声明、函数定义、函数调用的知识点。函数通过条件判断以及函数调用的方法实现求从m加到n的和,通过if语句对传入的n,m大小进行判断,如果m
当自定义函数在main()函数之前函数声明可以省略,之后必须进行函数声明;函数定义和传参是实参与形参的数量、顺序必须一致,函数声明和函数定义的参数数量和大小也必须一致