利用函数传递编写一个C语言程序,计算从x到y之间不能被3整除的数之和。(x,y由用户决定)
时间: 2024-05-08 17:19:36 浏览: 20
好的,这是一个计算问题,我可以给您提供C语言代码来实现这个功能。您可以参考下面的代码:
```c
#include <stdio.h>
int sum(int x, int y);
int main()
{
int x, y;
printf("请输入x和y的值,以空格分隔:");
scanf("%d %d", &x, &y);
printf("从%d到%d之间不能被3整除的数之和为:%d", x, y, sum(x, y));
return 0;
}
int sum(int x, int y)
{
int i, s = 0;
for (i = x; i <= y; i++)
{
if (i % 3 != 0)
{
s += i;
}
}
return s;
}
```
或者,您也可以将上述代码改为从命令行参数中读取x和y的值,代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
int sum(int x, int y);
int main(int argc, char *argv[])
{
int x = atoi(argv[1]);
int y = atoi(argv[2]);
printf("从%d到%d之间不能被3整除的数之和为:%d", x, y, sum(x, y));
return 0;
}
int sum(int x, int y)
{
int i, s = 0;
for (i = x; i <= y; i++)
{
if (i % 3 != 0)
{
s += i;
}
}
return s;
}
```
以上代码中,sum函数用于计算从x到y之间不能被3整除的数之和,main函数获取用户输入的x和y的值(第一个代码)或从命令行参数中获取(第二个代码),然后调用sum函数计算结果并输出。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)