【问题标题】:Constant Expression Required in c Programc程序中需要的常量表达式
【发布时间】:2020-10-18 11:01:06
【问题描述】:

以下代码显示错误“需要常量表达式”。我尝试了一些解决方案,但仍然无法解决。

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

int coins( int S[], int m, int n ) {
   int i, j, x, y;
   int table[n+1][m];
   for (i=0; i<m; i++)
      table[0][i] = 1;
   for (i = 1; i < n+1; i++) {
      for (j = 0; j < m; j++) {
         x = (i-S[j] >= 0)? table[i - S[j]][j]: 0;
         y = (j >= 1)? table[i][j-1]: 0;
         table[i][j] = x + y;
      }
   }
   return table[n][m-1];
}

int main() {
   int arr[20],n;
   int m,i;
   printf("********* MAKING CHANGE PROBLEM *********");
   printf("\nEnter size of array:");
   scanf("%d",&n);
   for(i=0;i<n;i++){
       scanf("%d",arr[i]);
   }
   m = sizeof(arr)/sizeof(arr[0]);
   printf("The total number of combinations of coins that sum up to %d",n);
   printf(" is %d ", coins(arr, m, n));
   getch();
   return 0;
}

【问题讨论】:

  • 你应该复制错误消息和它所指的行,不要指望人们尝试复制你的代码来找出错误所在。
  • 您没有显示应该指向行号的确切和完整的错误消息。所以猜测是这一行:int table[n+1][m]; Windows 编译器不支持可变长度数组 (VLA)。请改用malloc
  • scanf("%d",arr[i]); 这也是错误的。应该是scanf("%d",&amp;arr[i]);。编译器应该对此给出警告。
  • 输入n &gt; 20会发生什么?在输入n 之后,您应该遵循malloc 的建议。

标签: c windows for-loop conditional-operator


【解决方案1】:

根据C语言标准的不同版本,下面是不允许的,主要是这里产生的错误

int table[n+1][m];

改为使用 #define NSIZE 10#define MSIZE 20int table[NSIZE+1][MSIZE];etc

scanf("%d",arr[i]); 使用scanf("%d",&amp;arr[i]); 会导致问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多