【问题标题】:Binary search problem with my code....please look into my following problem?我的代码的二进制搜索问题....请查看我的以下问题?
【发布时间】:2011-03-29 15:04:34
【问题描述】:
#include<iostream>
#include<string>

using namespace std;

int main()
{
int list[25],vote[25];
bool found;
int count,first,mid,last;
char condition;
double high = 0,total=0;
string searchitem,name[25],winner;
cout <<"How many names?" <<endl;
cin>>count;
cout <<" Enter the "<<count<< " candidates last name and the number of votes received " <<endl;
for (int i=0;i<count;i++)
{
    cin >>name[i];
    cin >> vote[i];
    total = total+vote[i];

}

cout <<"Candidate names ,number of votes and their percentage of votes are ..."<<endl;
for (int i=0;i<count;i++)
{
    cout << name[i]<<endl;
    cout << vote[i]<<endl;
    cout << (vote[i]*100)/total<<endl;
    if(vote[i]>high)
    {
        high = vote[i];
     winner = name[i];
    }

}
cout << " The winner of the election is " << winner << endl;

cout << "Do you have anything more to do?y/n?" << endl;
cin >> condition;
while (condition=='y' || condition=='Y')
{
found = false;
cout<<"Enter name you want to search \n";
cin>>searchitem;
first=0;
last=count-1;
while ((first<=count)&&!found)
{
    mid=(first+last)/2;
    if (name[mid]==searchitem)
    {
        found=true;
        total =  total-vote[mid];
        cout << "Enter the new number of votes for " << name[mid] << endl;
        cin >> vote[mid];
        total = total + vote[mid];
    }
    else if (name[mid]>searchitem)
    {
        last=mid-1;
    }
    else first=mid+1;
}
if (!found)
{
    cout<<" Sorry that name was not found \n";
}

cout <<"Candidate names ,number of votes and their percentage of votes are ..."<<endl;
high = 0;
for (int i=0;i<count;i++)
{
    cout << name[i]<<endl;
    cout << vote[i]<<endl;
    cout << (vote[i]*100)/total<<endl;
    if(vote[i]>high)
    {
        high = vote[i];
     winner = name[i];
    }
}
cout << " The winner is " << winner << endl;

cout << "Do you have anything more to do?y/n? "<<endl;
cin >> condition;
}
}

好的。现在我一直在尝试对此进行试验,当涉及 5 个名字时,我能够更改第三个和第四个名字的投票并显示结果。 但是当我尝试搜索第一个、第二个和最后一个名字时,我的程序就停止了! 为什么会发生这种情况???而解决方案可以帮助我节省尝试徒手打破墙壁的时间。

【问题讨论】:

  • 1) 这不是一个真正的问题。 2)将功能拆分为子功能,太大了。 3)使用调试器或打印语句来弄清楚自己发生了什么
  • 1) 我的问题中显然有一个问题。 2) 我要求一种可以在我的代码中使用的解决方案,而不是用一种全新的方法来更改我的代码。
  • 您的问题只不过是“这是我编写的一些代码,为我修复”。如果你理解的足够写上面的,你应该可以自己调试了。

标签: c++ search binary-search


【解决方案1】:
while ((first<=count)&&!found)

应该是

while ((first<=last)&&!found)

【讨论】:

  • 这不起作用...现在每当我尝试搜索第一个、第二个和最后一个名字时,它都会显示为找不到该名称。
  • 你输入的名字是按顺序排列的吗?
  • 是的,我想知道。我有点忘了怎么做。但是我应该按照 A、B、C..etc 的顺序来命名吗?
  • 二分查找仅适用于已排序的数组。由于您正在对 name 数组应用二进制搜索。必须排序。
  • @Surya 二进制搜索需要有序序列。
猜你喜欢
  • 1970-01-01
  • 2022-12-08
  • 2017-03-04
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 2021-09-18
相关资源
最近更新 更多