挿入ソート機能に問題があります。私は投票と名前を降順で印刷しようとしていますが、投票は機能しているように見えますが、名前は降順ではなく昇順で印刷されています。私は投票の名前及び5 4 3 2 1 BのC D EがFに接続した後、それは次のようになりますC++での降順での挿入ソート
Please input the canditate 1 name:
a
Please input the canditate 1 votes:
1
Please input the canditate 2 name:
b
Please input the canditate 2 votes:
2
Please input the canditate 3 name:
c
Please input the canditate 3 votes:
3
Please input the canditate 4 name:
d
Please input the canditate 4 votes:
4
Please input the canditate 5 name:
e
Please input the canditate 5 votes:
5
Candidate Votes Received % of Total Votes
a 5 33.33
b 4 26.67
c 3 20.00
d 2 13.33
e 1 6.67
Total 15
The winner of the elections is a.
Program ended with exit code: 0
Press any key to continue . . .
候補ではなく、BはD = eのB E dがCである必要があります。
これは私のコードです。どんな助けもありがとう。
#include <iostream>
#include <string>
#include<iomanip>
using namespace std;
void insertionSort(double votes[], string name[], double len)
{
for (int i = 0; i < len - 1; i++)
{
int j = i + 1;
double temp = votes[j];
while (j > 0 && temp > votes[j - 1])
{
votes[j] = votes[j - 1];
j--;
votes[j] = temp;
}
string temp2 = name[j];
while (j > 0 && temp2 > name[j - 1])
{
name[j] = name[j - 1];
j--;
name[j] = temp2;
}
}
}
int main()
{
//Declaring variables
string *name;
double *votes;
double *percentage;
double total = 0;
int max = 0;
name = new string[5];
votes = new double[5];
percentage = new double[5];
//for condition for user to input Canditate names and the votes received
for (int i = 0; i < 5; i++)
{
cout << "Please input the canditate " << i + 1 << " " << "name: " << endl;
cin >> name[i];
cout << "Please input the canditate " << i + 1 << " " << "votes: " << endl;
cin >> votes[i];
total = total + votes[i];
}
//Q1 or Q2
//selectionSort(votes, name, 5);
insertionSort(votes, name, 5);
//printing out the Canditate, voters received, and % of total votes
cout << "Candidate" << "\t\t" << "Votes Received" << "\t\t" << "% of Total Votes" << endl;
//for loop in order to find % of total votes, winner of election
for (int i = 0; i < 5; i++)
{
if (votes[i]>votes[max])
max = i;
cout << name[i] << "\t\t\t" << fixed << setprecision(0) << votes[i] << "\t\t\t" << fixed << setprecision(2) << (votes[i] * 100/total) << endl;
}
//printing out the total and winner of the election
cout << "Total" << "\t\t\t" << fixed << setprecision(0) << total << endl;
cout << "The winner of the elections is " << name[max] << "." << endl;
delete[]name;
delete[]votes;
cout << "Program ended with exit code: 0" << endl;
return 0;
}
勧告:ユーザーの入力を削除し、配列に値のセットをハードコーディングします。このようにして、同じくりかえしを繰り返し入力する時間を節約できます。 2.タイプミスで壊れていない同じ入力を常にテストする。 3.あなたの正確なテストケースをインターネット上の私たちに提示する。 – user4581301