【问题标题】:Printing first array data amount of times based on second array data根据第二个数组数据打印第一个数组数据的次数
【发布时间】:2013-12-09 09:53:43
【问题描述】:

抱歉标题结构不佳,想不出如何措辞。

无论如何,当涉及到 C 中的数组和循环时,我遇到了一个问题。我需要让用户输入 5 个字母并将它们存储在第一个数组中。然后我需要他们输入 1 到 10 之间的 5 个数字并将它们存储在第二个数组中。然后我需要根据在第二个数组中输入的相应数字打印第一个数组的数据的次数。

例如,如果输入第一个数组的第一个字母是 A,输入第二个数组的第一个数字是 4,我需要打印出 AAAA。

我知道我需要在某个地方使用 for 循环,我确信这会比 while 循环更好,因为我会知道循环中使用的所有数据。

到目前为止,这是我的代码,虽然不多,但我讨厌问一个甚至没有代码的问题。

干杯!

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

int main() {

char input1[5];
int input2[5], i;

printf("Please enter a letter to be stored in the first array: \n");
scanf(" %c", &input1[0]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[1]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[2]);
printf("Please enter another letter to be stored in the first array: \n");
scanf(" %c", &input1[3]);
printf("Please enter a final letter to be stored in the first array: \n");
scanf(" %c", &input1[4]);
printf("The first array contains these values: %c, %c, %c, %c and %c. \n", input1[0],    input1[1], input1[2], input1[3], input1[4]);

printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[0]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[1]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[2]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[3]);
printf("Please enter five numbers between 1 and 10 to be stored in a second array: \n");
scanf("%d", &input2[4]);
printf("The second array contains these values: %d, %d, %d, %d and %d \n", input2[0], input2[1], input2[2], input2[3], input26[4]);

【问题讨论】:

    标签: c arrays for-loop


    【解决方案1】:
    for(i=0;i<5;i++){
      for(j=0;j<input2[i];j++){
        printf("%c",input1[i]);
      }
    }
    

    【讨论】:

      【解决方案2】:

      代码:

      for(i=0; i < input1.length; i++) {
         char charValue = input1[i];
         int loopNumber = input2[i];
         for(j=0 ;j < loopNumber; j++) {
            printf("%c" + charValue);
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多