我最近一直在建立一个程序:
a-zA-Z
值,否则会看到错误。包含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 ++业余爱好者,因为我几天前就选择了这种语言。
感谢。
编辑:编辑标题以适应实际问题,如评论中所示。
答案 0 :(得分:3)
一种可能的方法是对数组进行排序,然后迭代计数当前字母。当字母更改时(例如,从您的示例中的'A'
到'F'
),打印字母和计数。重置计数器并继续计算下一个字符。
答案 1 :(得分:0)
主循环应在字符串中运行foreach字符。
每次主要&#34;经过&#34;时,二级循环应该运行。检查当前字母是否在数组中。如果它在那里,那么++。
答案 2 :(得分:0)
假设大写和小写字母被认为是相等的(否则,你需要一个比建议大小两倍的数组:
std::array<unsigned int, 26> counts; //!!!
// get number of characters to read
for(unsigned int i = 0; i < charactersToRead; ++i)
{
char c; // get a random value or read from console
// range check, calculate value in range [0; 25] from letter...
// now the trick: just do not store the value in an array,
// evaluate it d i r e c t l y instead:
++counts[c];
}
// no a d d i t i o n a l array so far...
char c = 'a';
for(auto n : counts)
{
if(n > 0) // this can happen now...
{
// output c and n appropriately!
}
++c; // only works on character sets without gaps in between [a; z]!
// special handling required if upper and lower case not considered equal!
}
旁注:(参见CiaPan对该问题的评论):如果只计算真正的重复项,则必须在最后一个循环中if(n > 1)
!
答案 3 :(得分:0)
添加数组char chars[52]
并计算此数组中的字符数。然后打印出与数组对应的字符,其数量大于1。
std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
++chars[c];
else if ('a' <= c && c <= 'z')
++chars[c];
else
// unexpected char
...
for (const auto p : chars)
std::cout << p.first << ": " << p.second << " ";