简单数组工作不正常
Simple array not working right
这应该模拟投掷2个6面骰子,将+1添加到熟悉结果的数组元素中。例如:a[4]表示滚动了多少个4。出于某种原因,无论它滚动多少次,它都会为数组中的每个元素提供1。I.e:(a[2]=1,a[3]=1,a[4]=1等)
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice() // generates random number ranging 2-12
{
int x = (rand() % 6) + 1;
int p = (rand() % 6) + 1;
return x + p;
}
int main()
{
srand (time(NULL));
int y;
cout << "Roll dice how many times?" << endl;
cin >> y;
int a2[12]; // initializes and declares elements a[2] - a[12] with value 0
for (int i = 2; i <= 12; i++)
a2[i] = 0;
for (int i = 0; i <= y; i++) // runs random number generator, adds +1 to that element
{
a2[throwDice()]++;
}
for (int i = 2; i <= 12; i++) // prints how many results per element
cout << i << " = " << throwDice[i] << endl;
system("pause");
}
cout << i << " = " << throwDice[i] << endl;
应该是
cout << i << " = " << a2[i] << endl;
编译代码时应该始终使用-Wall
,这会立即向您显示出问题:
Compilation finished with warnings:
source.cpp: In function 'int main()':
source.cpp:33:38: warning: pointer to a function used in arithmetic
[-Wpointer-arith]
此外,数组索引从0开始,因此为了能够访问a2[12]
,它必须具有至少13的大小。
最后,system("pause");
是一个值得怀疑的想法。我更喜欢cin.get();
等待用户按下任何键。
相关文章:
- 不确定要在我的main中放入什么才能使我的代码正常工作
- C++中的memset函数工作不正常
- 为什么 HeapFree() 不能正常工作?
- 如果不在窗口 10 中声明名为 openCV 的 openCV namedWindow,QT 图像显示将无法正常工作
- 通用线程池类工作不正常
- 循环仅对第一行正常工作.其他行不受 for 的影响
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- C++自定义删除运算符不能正常工作?
- 为什么使用 exec() 重新启动程序不能正常工作?
- C++:返回本地对象,但不能正常工作
- 名为DLL的C++windows服务程序工作不正常
- C++-循环中的If语句工作不正常
- 为什么带lcov的codecov在Travis上不能正常工作,而在我当地的Linux Mint上却不能正常工作
- While循环和if/else语句工作不正常
- 为什么sizeof函数在这里不能正常工作
- 异步操作的 Asio 处理程序在其同步对应项正常工作时不会调用
- C++:最大数组值函数工作不正常
- 图像上的按钮不正常工作在QT
- 透明SDL2游戏(WIN32色键不正常工作)
- Qt 5.3 QSystemTrayIcon不正常工作[Linux]