尽管我有 C++ 经验,但我对 C 还比较陌生。我正在编写一个程序,该程序接受用户输入的数组长度和操作变量,并且我试图通过 scanf 提示来完成此操作。我不确定是否是因为我的设置方式所致,但我的程序在输入数组长度值后关闭之前有一个短暂的延迟。我假设延迟是程序读取并跳过代码中的所有其他行。
这是我现在拥有的代码。可能还有其他问题,但在我的输入得到修复之前我无法检查。
// Input: The first line of the input contains an integer N and t (3 <= N <= 200000; 1 <= t <= 7)
// Output: For each test case, output the required answer based on the value of t.
#include <stdio.h>
int main(){
// Initialize integer N and t for inputting.
int N, t;
scanf("%d", N);
scanf("%d", t);
// Initialize array for inputting components.
int A[N];
for(int c = 0; c < N; c++){
scanf("%d", A[c]);
}
switch(t){
// Print 7, regardless of array A's contents
case 1:
printf("%d\n, 7");
// Print "Bigger" if A[0] > A[1] or "Equal" if A[0] == A[1]. Otherwise, print "Smaller".
case 2:
if(A[0] > A[1]){
printf("%d\n, Bigger");
}
else if(A[0] == A[1]){
printf("%d\n, Equal");
}
else{
printf("%d\n, Smaller");
}
// Print the median of the first three indexes of the A array.
case 3:
printf("%d\n, (A[0]+A[1]+A[2])/2");
// Print the sum of all integers in A.
case 4:
printf("%d\n, Sum(A, N)");
// Print the sum of all EVEN integers in A.
case 5:
printf("%d\n, evSum(A, N)");
// Apply %26 to each integer in the A array, map integers from 0-25 to the alphabet,
// and print the new sequence of characters as a string.
case 6:
// Figuring this one out
printf("\nStub");
// Start from index i = 0; Jump to index i = A[i]; If the current index is outside
// the valid bound from 0 to N-1, print "Out" and exit. Else, if the
// current index is the index N-1, print "Done" and exit, otherwise go back
// to step b. If doing this leads to an infinite loop, print "Cyclic" and exit.
case 7:
// Figuring this one out
printf("\nStub");
}
return 0;
}
// Integer function that returns the sum of all the integers in the inputted array.
// Apparently, you also need to add the length of the array externally, since it wont just let me use 'N'.
int sum(int* array[], int arrayLength){
int k = 0;
for(int o = 0; o < arrayLength; o++){
k = k + *array[o];
}
return k;
}
// Integer function that returns the sum of all the even integers in the inputted array.
// To check if an integer is even, it checks if the modulo of 2 for the integer is equal to 0.
// Apparently, you also need to add the length of the array externally, since it wont just let me use 'N'.
int evSum(int* array[], int arrayLength){
int l = 0;
for(int m = 0; m < arrayLength; m++){
if(*array[m] % 2 == 0){
l = l + *array[m];
}
return l;
}
}
我希望至少能够检查我的代码,以确保我的求和函数在弄清楚我的第六个和第七个案例之前工作正常
当您传递已初始化变量的值而不是对其的引用时,您的程序会调用未定义的行为。
您还需要检查 scanf 是否没有失败:
int N, t;
if(scanf("%d", &N) != 1) {/* handle error */}
if(scanf("%d", &t) != 1) {/* handle error */}
还有
printf("%d\n, 7");
在格式之后期待一个参数(但我认为它是一种类型,因为你在这里有逗号)。
printf("%d\n", 7);
/* or simple*/
printf("7\n");