c - Kochan Book : Programming in C i + j - i % j 中的一项练习遇到问题

标签 c

这是我的 C 源代码:

details that stackoverflow want to see or i can't edit

#include <stdio.h>

int main (void) {

    int  i, j;

    int Next_multiple = (i + j) - (i % j);

    i = 365;
    j = 7;

    printf("Solution for i == 365 j == 7 = %i \n", Next_multiple);

    i = 12258;
    j = 23;

    printf("Solution for i == 12258 j == 23 = %i \n", Next_multiple);

    i = 996;
    j = 4;

    printf("Solution for i== 996 j == 4 = %i \n", Next_multiple);

    return 0;
}

这就是输出:

.exe(Visual Studio 工具中的 Windows cmd)

Solution for i == 365 j == 7 = 18039659

Solution for i == 12258 j == 23 = 18039659

Solution for i== 996 j == 4 = 18039659

最佳答案

  1. 当您使用未初始化的局部变量 i 和 j 时,您会出现未定义的行为。

然后显示 3 倍相同的计算变量(使用这些随机值)。该如何整理呢?

1 将此函数放在 main 函数之前。

  int Next_multiple(int i, int j)
  {
     return ( i + j) - (i % j);
   }

改变

printf("Solution for i == 12258 j == 23 = %i \n", Next_multiple);

  printf("Solution for i == 12258 j == 23 = %i \n", Next_multiple(i, j));

并删除

 int Next_multiple = (i + j) - (i % j);
<小时/>
#include <stdio.h>

int Next_multiple(int i, int j)
{
   return ( i + j) - (i % j);
}
int main () {

    int  i, j;

    i = 365;
    j = 7;

    printf("Solution for i == 365 j == 7 = %i \n", Next_multiple(i,j));

    i = 12258;
    j = 23;

    printf("Solution for i == 12258 j == 23 = %i \n", Next_multiple(i,j));

    i = 996;
    j = 4;

    printf("Solution for i== 996 j == 4 = %i \n", Next_multiple(i,j));

    return 0;
}

关于c - Kochan Book : Programming in C i + j - i % j 中的一项练习遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45496593/

相关文章:

c - 如何将数组从 .Net 传递到 C?

c - NXT-G可视化编程与乐高积木NXC类C编程的区别

c - GTK+ :How to communicating between GtkWindow?

c - 为什么要使用 _mm_malloc? (相对于 _aligned_malloc、alligned_alloc 或 posix_memalign)

c - + 或 - 登录数组,C

c++ - pthread_key_t 与局部变量

iphone - 如何使用 CFURLCreateFromFileSystemRepresentation

c - 取消引用指向结构的指针以访问其第一个成员

c - 调整数组中的位置以保持递增顺序

c - DEV-C++ 通知 : _CRTIMP int_ccdecl printf(const char*, ...)