#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 次。
我想问
我的代码逻辑有问题吗? (我想我的代码确实有问题所以请赐教)
当我必须不断更改变量的值时,使用指针指向上述变量的内存地址会更好(甚至可能)吗?如果是,我该怎么做?
谢谢!
最佳答案
在 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/