【问题标题】:for loop resulting in undefined behaviour cfor 循环导致未定义的行为 c
【发布时间】:2018-06-03 11:21:53
【问题描述】:
#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 中使用&amp;
  • 我意识到这可能是由于我对 scanf 的不当使用导致了未定义的行为。有什么想法吗?
  • 您不需要在 printf 中取消引用。您将指针传递给 scanf 函数,以便它可以将整数放在其范围之外的变量中。您将值传递给 printf。同样在通过scanf获取值之前定义了ans,您需要在scanf调用之后进行计算。
  • @PaulOgilvie 啊,我明白了!但是,我的回答仍然给出了一个输出,表明仍然存在未定义的行为
  • @sacko87 所以我可以将计算放在循环中吗?这会导致我在“ans”变量中创建一个数组吗?

标签: c pointers for-loop undefined-behavior


【解决方案1】:

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);

【讨论】:

  • “有一个前导空格”是不必要的。 scanf("%d"... 跳过前导空格。
  • @chux, I read "一个空白字符导致 scanf 读取,但不存储输入中所有连续的空白字符,直到下一个非空白字符”。 (但我不是 scanf 的专家——我应该调整我的答案吗?)
  • 不是空白字符的问题。这是"%d" 所做的,其中包括“跳过输入空白字符(由isspace 函数指定),除非规范包含[cn 说明符”C11 § 7.21.6.2 7. 使用该功能,前导" " 是多余的。随心所欲地调整。
【解决方案2】:

您看到的是变量内存位置的值。 如下更改 for 循环内的行

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

【讨论】:

    【解决方案3】:

    你的代码有一些错误。

    1. 您在 print 语句中使用了 & 运算符,用于打印变量的地址。

    2. 使用值“1”而不是“0”启动循环并执行循环直到“i”小于等于“n”。

    3. 不要在循环外使用 ans 变量,而是在循环内使用它,因为它在循环的每次迭代中计算乘法结果。

    #include <stdio.h>
    
    int main()
    {
        int i;
        int mult;
        int n;
        int ans;
    
        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 = 1; i<=n; i++) {
            ans = mult*i ;
            printf("%d x %d = %d \n", mult, i , ans);
        }
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 2022-01-19
      相关资源
      最近更新 更多