卓越精算t3破解版提示GDmain index -1 out of range

C++:我用Visual Studio 2010运行如下程序时,提示:vector subscript out of range;请问各位高手该怎么解_百度知道
C++:我用Visual Studio 2010运行如下程序时,提示:vector subscript out of range;请问各位高手该怎么解
我用Visual Studio 2010运行如下程序时,提示:vector subscript out of range;请问各位高手该怎么解决此问题,小生不胜感激!#include&iostream&#include&vector&
int main(){
vector&string& vec1(1,&C++&),vec2;
for(vector&int&::size_type index=0;index!=vec1.size();++index) {
vec2[index]=vec1[index];
cout&&vec2[index]; } cout&&
return 0;}
提问者采纳
#include &iostream&#include &vector&#include &string& int main(int argc, char* argv[]){
vector&string& vec1(1, &C++&), vec2(1); // 要给vec2初始化空间,不然你用vec2[index]就取到非法内存地址了.
for (vector&int&::size_type index=0; index!=vec1.size(); ++index)
vec2[index] = vec1[index];
cout && vec2[index];
cout &&return 0;}
提问者评价
按照你说的,真的成功了,好开心,谢谢你!
其他类似问题
为您推荐:
vector的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁python实例程序运行时报错:“IndexError: list index out of range”_百度知道
提问者采纳
sys.argv[1] 表示取命令行的第一个参数,但是你在调用test06.py的时候没有加任何参数,所以数组当然就越界了, 从这个代码来看,你应该在test06.py后面加一个网址,比如
这样就可以了。
已成功。谢谢。初学者多谢指教。
提问者评价
其他类似问题
为您推荐:
python的相关知识
其他1条回答
就是url没有取值,sys.argv[1],代表命令行的参数,你可以在运行文件的时候加一个网址,python test06.py
这样就可以了。否则的话,sys.argv只存在sys.argv[0],他的值是运行文件的名称,也就是test06.py.所以会提示数组越界
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
## A little helper program that capitalizes the first letter of a word
def Cap (s):
s = s.upper()[0]+s[1:]
Giving me this error :
Traceback (most recent call last):
File "\\prov-dc\students\jadewusi\crack2.py", line 447, in &module&
sys.exit(main(sys.argv[1:]))
File "\\prov-dc\students\jadewusi\crack2.py", line 398, in main
foundit = search_method_3("passwords.txt")
File "\\prov-dc\students\jadewusi\crack2.py", line 253, in search_method_3
ourguess_pass = Cap(ourguess_pass)
File "\\prov-dc\students\jadewusi\crack2.py", line 206, in Cap
s = s.upper()[0]+s[1:]
IndexError: string index out of range
390k38797983
As others have already noted, the problem is that you're trying to access an item in an empty string. Instead of adding special handling in your implementation, you can simply
'hello'.capitalize()
=& 'Hello'
''.capitalize()
20.9k32759
It blows up, presumably, because there is no indexing an empty string.
Traceback (most recent call last):
File "&stdin&", line 1, in &module&
IndexError: string index out of range
And as it has been pointed out, splitting a string to call str.upper() on a single letter can be supplanted by str.capitalize().
Additionally, if you should regularly encounter a situation where this would be passed an empty string, you can handle it a couple of ways:
…#whatever previous code comes before your function
if my_string:
Cap(my_string)
#or str.capitalize, or…
if my_string being more or less like if len(my_string) & 0.
And there's always ye old try/except, though I think you'll want to consider ye olde refactor first:
#your previous code, leading us to here…
Cap(my_string)
except IndexError:
I wouldn't stay married to indexing a string to call str.upper() on a single character, but you may have a unique set of reasons for doing so. All things being equal, though, str.capitalize() performs the same function.
&&& s = 'macGregor'
&&& s.capitalize()
'Macgregor'
&&& s[:1].upper() + s[1:]
'MacGregor'
&&& s = ''
Traceback (most recent call last):
File "&stdin&", line 1, in &module&
IndexError: string index out of range
&&& s[:1].upper() + s[1:]
Why does s[1:] not bail on an empty string?
Degenerate slice indices are handled gracefully: an index that is too
large is replaced by the string size, an upper bound smaller than the
lower bound returns an empty string.
See also .
136k27237371
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabledStack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
it's me again. I think I have my program completed, but... it doesn't work. I'm trying to write a program that simulates a lottery game, but when I try to check the user's guesses against the number of guesses on the ticket, I get an error that tells me the "list index is out of range". I think it has something to do with the part of the code where I assign the random digits to "a," "b", "c", etc. But I'm not sure.
Here is the code in it's entirety:
import random
def main():
random.seed()
#Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))
#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
guess = []
winnings = 0
#Generates the winning lotto numbers.
for i in range(tickets):
del winning_numbers[:]
a = random.randint(1,30)
while not (a in winning_numbers):
winning_numbers.append(a)
b = random.randint(1,30)
while not (b in winning_numbers):
winning_numbers.append(b)
c = random.randint(1,30)
while not (c in winning_numbers):
winning_numbers.append(c)
d = random.randint(1,30)
while not (d in winning_numbers):
winning_numbers.append(d)
e = random.randint(1,30)
while not (e in winning_numbers):
winning_numbers.append(e)
print(winning_numbers)
getguess(guess, tickets)
nummatches = checkmatch(winning_numbers, guess)
print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
if nummatches == 0 or nummatches == 1:
winnings = winnings + 0
elif nummatches == 2:
winnings = winnings + 10
elif nummatches == 3:
winnings = winnings + 500
elif nummatches == 4:
winnings = winnings + 20000
elif nummatches == 5:
winnings = winnings + 1000000
print("You won a total of",winnings,"with",tickets,"tickets.\n")
#Gets the guess from the user.
def getguess(guess, tickets):
del guess[:]
for i in range(tickets):
bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
guess.append(bubble)
print(bubble)
#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
for i in range(5):
if guess[i] == winning_numbers[i]:
match = match+1
return match
And here is the error I get:
Traceback (most recent call last):
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 85, in &module&
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 45, in main
nummatches = checkmatch(winning_numbers, guess)
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 79, in checkmatch
if guess[i] == winning_numbers[i]:
IndexError: list index out of range
Thanks for your help again.
As the error notes, the problem is in the line:
if guess[i] == winning_numbers[i]
The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:
for i in range(tickets):
bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
guess.append(bubble)
print(bubble)
The size of how many guesses you are giving your user is based on
# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))
So if the number of tickets they want is less than 5, then your code here
for i in range(5):
if guess[i] == winning_numbers[i]:
match = match+1
return match
will throw an error because there simply aren't that many elements in the guess list.
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).
Here is your code. I'm assuming you're using python 3 based on the your use of print() and input():
import random
def main():
#random.seed() --& don't need random.seed()
#Prompts the user to enter the number of tickets they wish to play.
#python 3 version:
tickets = int(input("How many lottery tickets do you want?\n"))
#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
winnings = 0
#Generates the winning lotto numbers.
for i in range(tickets * 5):
#del winning_numbers[:] what is this line for?
randNum = random.randint(1,30)
while randNum in winning_numbers:
randNum = random.randint(1,30)
winning_numbers.append(randNum)
print(winning_numbers)
guess = getguess(tickets)
nummatches = checkmatch(winning_numbers, guess)
print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
winningRanks = [0, 0, 10, 500, 20]
winnings = sum(winningRanks[:nummatches + 1])
print("You won a total of",winnings,"with",tickets,"tickets.\n")
#Gets the guess from the user.
def getguess(tickets):
guess = []
for i in range(tickets):
bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
guess.extend(bubble)
print(bubble)
return guess
#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
for i in range(5):
if guess[i] == winning_numbers[i]:
match += 1
return match
11.9k11638
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Stack Exchange
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled能否帮忙看一下关于String index out of range: -1的错误_百度知道
能否帮忙看一下关于String index out of range: -1的错误
这是一个Java的管理系统,其中有一个模块无法使用,提示出现String index out of range:-1的问题。不知道是不是这句出现了问题,我的经验不太多。&A href=&&%=basePath%&newsinfo.jsp?id=&%=allnew.get(0).toString()%&& &&%=allnew.get(1).toString()%&&/A&不知如何解决。请大神指点一下,谢谢!
给出的代码只会出现异常java.lang.IndexOutOfBoundsException: Index: 0, Size: 0,但是你的是String index out of range: -1,这个是说字符索引越界了。给你两个例子说明:‍java.lang.IndexOutOfBoundsException: Index: 0, Size: 0&import&java.util.ArrayLimport&java.util.Lpublic&class&Test&{&public&static&void&main(String[]&args)&{&&List&String&&list&=&new&ArrayList();&&list.get(0);//&&String&str&=&&abc&;//&&str.substring(4);&}}结果:&2、java.lang.StringIndexOutOfBoundsException: String index out of range:-1import&java.util.ArrayLimport&java.util.Lpublic&class&Test&{&public&static&void&main(String[]&args)&{//&&List&String&&list&=&new&ArrayList();//&&list.get(0);&&String&str&=&&abc&;&&str.substring(4);&}}结果:上面的str.substring(4)里面的4改成5,-1就变成-2了。上面可以看出出现你那个错误就可能是你的某个地方对字符串进行了操作。一般如果在jsp页面用了substring这个函数可能出现。如果不是这个函数的问题,你可以用、StringIndexOutOfBoundsException这个类名在String类源码里面搜索下,可以看到有哪几个函数会抛出这个异常。比如下面的代码是String类里面的charAt函数:&&&&public&char&charAt(int&index)&{&&&&&&&&if&((index&&&0)&||&(index&&=&count))&{&&&&&&&&&&&&throw&new&StringIndexOutOfBoundsException(index);&&&&&&&&}&&&&&&&&return&value[index&+&offset];&&&&}如果在操作字符串的时候你没有胡乱的指定索引,即比如charAt函数,一般不会指定负数这样的索引,所以不会出现上面的异常值-1,按惯例来看,String 里面只有三个(重载不算)会异常值为负数的情况。而这三个也就substring比较常用.代码如下:&public&String&substring(int&beginIndex,&int&endIndex)&{&if&(beginIndex&&&0)&{&&&&&throw&new&StringIndexOutOfBoundsException(beginIndex);&}&if&(endIndex&&&count)&{&&&&&throw&new&StringIndexOutOfBoundsException(endIndex);&}&if&(beginIndex&&&endIndex)&{&&&&&throw&new&StringIndexOutOfBoundsException(endIndex&-&beginIndex);&}&return&((beginIndex&==&0)&&&&(endIndex&==&count))&?&this&:&&&&&new&String(offset&+&beginIndex,&endIndex&-&beginIndex,&value);&&&&}&如果确实是substring函数的问题,请在jsp页面下使用struts2标签或者c标签等判断下字符串的长度在进行截取。&如含有问题,可以给我发邮箱
来自团队:
其他类似问题
为您推荐:
string的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁

我要回帖

更多关于 卓越精算t3教程 的文章

 

随机推荐