【问题标题】:Why does the "for" loop not work and program stops?为什么“for”循环不起作用并且程序停止?
【发布时间】:2020-11-24 16:21:02
【问题描述】:

当我编译程序时,它似乎可以正常工作,但是当它要求“cuadrados”时,程序就停止了:

int main(){

int *ptrs, suma=0, n, i, m;

printf("cuantos numeros al cuadrado quiere?: ");
scanf("%i", &n);

int numero[n], cubo[n];
*ptrs=numero

这是程序停止的时间:

for(i=0;i<n;i++){
printf("escriba los cuadrados: "); 
scanf("%i", numero[i]);

}


printf("Cuantos numero al cubo quiere?: ");
scanf("%i", m);

 for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", cubo[i]);
}

我之前遇到过这个问题,但我不明白为什么它没有继续运行;它只要求输入 1 个数字,然后在没有错误或警告的情况下停止。

【问题讨论】:

  • “它停止编译”是什么意思?你的意思是它停止执行并等待输入吗?你提供输入吗?你的意见是什么?
  • 你必须像第一次一样将变量的地址传递给scanf()。所以scanf("%i", m); 必须是scanf("%i", &amp;m); 和类似的数组,我让你弄清楚它们。编译器没告诉你吗?

标签: c


【解决方案1】:
for(i=0;i<n;i++){
printf("escriba los cuadrados: "); 
scanf("%i", &numero[i]);
}

printf("Cuantos numero al cubo quiere?: ");
scanf("%i", &m);

 for(i=0;i<n;i++){
printf("escriba los cubos: ");
scanf("%i", &cubo[i]);
}

您需要使用&amp; 运算符在scanf 中提供变量的地址

【讨论】:

    【解决方案2】:

    这会崩溃,因为 scanf 需要一个 pointer-to-int,而不是 int:

    scanf("%i", numero[i]);
    

    这不会:

    if (scanf("%i", &numero[i]) == 1) {
        /* do something */
    }
    else {
         /* scanf failed */
    }
    

    请注意,不测试scanf 返回值总是自找麻烦。就像没有使用编译器的最大警告级别并将所有警告变成错误一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2013-10-17
      • 2021-05-13
      • 1970-01-01
      • 2016-03-16
      • 2018-09-12
      • 2013-12-13
      相关资源
      最近更新 更多