我必須生成一個包含 0、1 或 2 的隨機陣列,并用特定字符交換這些陣列。例如:每個 1 都應顯示為“B”。我得到了我的隨機陣列,但我不知道如何換出陣列中的變數。只能在印刷品中替換數字。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
#define M 5
void print_array();
char get_symbol();
int main(void) {
int i, j;
int a[M][N];
srand(time(NULL)); // Initialisiere Zufallsgenerator
// Weise den Elementen des Arrays Zufallszahlen zu
for (i = 0; i < M; i ) { //i-te Zeile
for (j = 0; j < N; j ) { //j-te Spalte
a[i][j] = (rand() % 3); // Erzeuge Zufallszahl
}
}
print_array(a, M, N);
}
void print_array(int a[][N], int m, int n) {
int i, j;
printf("Spalte : ");
for (j = 0; j < n; j ) {
printf("%d ", j 1);
}
printf("\n\n");
for (i = 0; i < m; i ) {
printf("Zeile %d: ", i 1);
for (j = 0; j < n; j ) {
printf("%d ", a[i][j]);
}
printf("\n");
}
}
// this function is only returning "B"
void print_array(int a[][N], int m, int n) {
int i, j;
printf("Spalte : ");
for (j = 0; j < n; j ) {
printf("%d ", j 1);
}
printf("\n\n");
for (i = 0; i < m; i ) {
printf("Zeile %d: ", i 1);
for (j = 0; j < n; j ) {
if (a[i][j] = 0) {
printf("A");
}
else if(a[i][j] = 1) {
printf("B");
}
else {
printf("C");
}
}
printf("\n");
}
}
uj5u.com熱心網友回復:
您正在使用“=”而不是“==”來比較 if else 條件中的兩個值。
for (j = 0; j < n; j ) {
if (a[i][j] = 0){
printf("A");
}
else if(a[i][j] = 1){
printf("B");
}
else{
printf("C");
}
}
當你做相反的事情時,你必須比較未分配的值。
for (j = 0; j < n; j ) {
if (a[i][j] == 0){
printf("A");
}
else if(a[i][j] == 1){
printf("B");
}
else{
printf("C");
}
}
用上面的代碼替換你的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/488062.html
標籤:C
