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

问题描述 投票:0回答:3
#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. 当我不得不经常更改变量的值时,使用指针指向所提及变量的内存地址会更好(甚至可能)吗?如果是的话,我该怎么做呢?

谢谢!

c pointers for-loop undefined-behavior
3个回答
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);


You should also check the return value of scanf to check if it has succeeded reading your input:
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);

1
投票

你看到的东西是变量内存位置的值。如下所示,在for循环中更改你的行

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

1
投票

您的代码中存在一些错误。

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.