c语言取余数
时间: 2023-07-02 10:04:32 浏览: 98
在C语言中,我们可以使用%运算符来求取两个数的余数。例如,a % b表示a除以b的余数。下面是一个示例代码:
```c
#include <stdio.h>
int main() {
int a = 10;
int b = 3;
int c = a % b;
printf("a mod b = %d\n", c);
return 0;
}
```
输出结果为:
```
a mod b = 1
```
因为10除以3的余数是1。
相关问题
大数对大数求余数c语言函数
以下是一个C语言函数,可以用于大数对大数求余数:
```c
#include <stdio.h>
#include <string.h>
int mod(char a[], int b)
{
int len = strlen(a);
int ans = 0;
for (int i = 0; i < len; i++) {
ans = (ans * 10 + a[i] - '0') % b;
}
return ans;
}
int main()
{
char a[1000];
int b;
printf("请输入大数a:");
scanf("%s", a);
printf("请输入大数b:");
scanf("%d", &b);
printf("a %% b = %d\n", mod(a, b));
return 0;
}
```
该函数的原理是将大数a转换为整数,然后对b取余数。具体实现过程是将a中的每个字符转换为数字,然后用ans记录当前余数,每次将ans乘以10再加上当前数字,最后对b取余数即可。
c++中可以对0取余数吗
在C语言中,对于整数类型的数,不能对0取余数,这是因为任何数除以0都是没有定义的(undefined)。在对0取余数的操作中,计算机将试图将0作为一个被除数来计算余数,但由于除以0是无意义的,计算机将无法执行此操作,因此会导致程序错误并可能崩溃。因此,在C语言中,如果试图对0取余数,会导致运行时错误(runtime error)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)