c - for 循环导致未定义的行为 c

标签 c pointers for-loop undefined-behavior

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    int mult;
    int n;
    int ans;
    ans = mult * i;

    printf("Please enter a multiple you want to explore.");
    scanf("%d", &mult);
    printf("Please enter the number which you would want to multiply this number till.");
    scanf("%d", &n);

    for(i = 0; i<n; i++) {
        printf("%d x %d = %d \n", &mult, &i , &ans);
    }
    return 0;
}

大家好,这是一个简单的代码,旨在帮助用户列出 n 次乘法表。但是,我收到未定义的行为,我对我的“for”循环的实现有什么问题感到很困惑。

我收到这个作为我的输出。

6356744 x 6356748 = 6356736 

在我的控制台中 n 次。

我想问

  1. 我的代码逻辑有问题吗? (我想我的代码确实有问题所以请赐教)

  2. 当我必须不断更改变量的值时,使用指针指向上述变量的内存地址会更好(甚至可能)吗?如果是,我该怎么做?

谢谢!

最佳答案

printf 中,您必须提供整数。您现在给出整数的地址。所以改变

printf("%d x %d = %d \n", &mult, &i , &ans);

printf("%d x %d = %d \n", mult, i, ans);

为了制作表格,将 ans 替换为 mult*i,所以:

printf("%d x %d = %d \n", mult, i, mult*i);


您还应该检查 scanf 的返回值以检查它是否已成功读取您的输入:

do {
    printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
    printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);

关于c - for 循环导致未定义的行为 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50665829/

相关文章:

c - 指向一维数组和二维数组有什么区别?

pointers - Golang 中 []*Users 和 *[]Users 的区别?

iphone - 将 UInt32(音频帧)拆分为两个 SInt16(左右)?

r - R : how to initialize and add elements to an array in a loop

c - OpenMP 并在 DFS 树的特定级别打开并行化

c - 查看 typedef 替换

c - execv 未知路径使用情况

使用指针将浮点矩阵复制并转换为 double 矩阵

python - 在 Python 中使用列表方法加速 for 循环

java - for循环只读取最后一个值