gpt4 book ai didi

c++ - 计算 C++ 中相同数组值的出现次数

转载 作者:行者123 更新时间:2023-11-30 02:20:27 25 4
gpt4 key购买 nike

我最近一直在构建一个程序,其中:

  1. 要求用户输入一个代表字符数组大小的数字。
  2. 然后询问他们是否希望程序自动填充值,或者他们可以按 M 以便手动输入值。他们只能输入 a-zA-Z 值,否则他们会看到错误。
  3. 在程序的最后,我需要统计每一个重复的值并显示出来,例如:

5 个字符的数组由 A;A;A;F;G; 组成

输出应该是这样的:

A - 3

F - 1

G - 1

我本来可以轻松做到这一点,但是,老师说我可能不会使用额外的数组,但是我可以很好地使用更多的变量,而且我也不能使用开关元素。我完全迷路了,我找不到解决办法。我在下面添加了代码。除了计数部分,我什么都做了。

#pragma hdrstop
#pragma argsused

#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>

void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;

clrscr();

cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";

cout << "Your choice (M/A): ";
cin >> masiva_izvele;

if (masiva_izvele == 'M' || masiva_izvele == 'm') {
clrscr();
for (i = 0; i < n; i++) {
do {
cout << "Enter " << i + 1 << " array element: ";
flushall();
cin >> masiva_burts;
cout << endl << int(masiva_burts);
if (isalpha(masiva_burts)) {
clrscr();
array[i] = masiva_burts;

}
else {
clrscr();
cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
}
}
while (!isalpha(masiva_burts));
}


}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
clrscr();
for (i = 0; i < n; i++) {

array[i] = rand() % 25 + 65;

}
}

clrscr();

cout << "Masivs ir izveidots! \nArray size is " << n <<
"\nArray consists of following elements:\n\n";

for (i = 0; i < n; i++) {

cout << array[i] << "\t";

}



cout << "\n\nPress any key to view the amount of every element in array.";

//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.

getch();

}

我会非常感谢一个解决方案,这样我就可以继续前进并原谅我的 C++ 业余爱好者,因为我几天前才选择这门语言。

谢谢。

编辑:根据评论中的建议编辑标题以适应实际问题。

最佳答案

一种可能的方法是对数组进行排序,然后迭代它计算当前字母。当字母发生变化时(例如从 'A''F' 如您的示例所示)打印字母和计数。重置计数器并继续计算下一个字符。

关于c++ - 计算 C++ 中相同数组值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49625765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com