【发布时间】:2018-01-29 04:24:17
【问题描述】:
我需要创建一个程序来获取 6 个随机整数输入(3 个偶数,3 个奇数;以任意顺序),然后显示输入的最小偶数和奇数整数。我的代码几乎完全做到了这一点,除非您为第一个变量输入一个数字,例如 -6 并一直到最后一个变量为 -1,最小的偶数被计为 -4,最小的奇数是 -5。究竟是什么问题导致了这种情况发生?
short int a, b, c, d, e, f, smallEven=0, smallOdd=0;
cout<<"Enter a number: "; //test a-c: even or odd; is there a small even or small odd; if there is, is new input smaller than old?
cin>>a;
if (a%2==0){
if (smallEven==0)
smallEven=d;
else if (a<smallEven)
smallEven=a;
}
else if (a%2== 1 || a%2== -1){
if (smallOdd==0)
smallOdd=a;
else if (a<smallOdd)
smallOdd=a;}
cout<<"Enter a number: ";
cin>>b;
if (b%2==0){
if (smallEven==0)
smallEven=b;
else if (b<smallEven)
smallEven=b;
}
else if (b%2==1 || b%2== -1){
if (smallOdd==0)
smallOdd=b;
else if (b<smallOdd)
smallOdd=b;}
cout<<"Enter a number: ";
cin>>c;
if (c%2==0){
if (smallEven==0)
smallEven=c;
else if (c<smallEven)
smallEven=c;
}
else if (c%2== 1 || c%2== -1){
if (smallOdd==0)
smallOdd=c;
else if (c<smallOdd)
smallOdd=c;}
cout<<"Enter a number: "; //at this point only need to ask if input is even or odd, and if its the smallest
cin>>d;
if (d%2==0){
if (d<smallEven)
smallEven=d;
}
else if (d%2== 1 || d%2== -1){
if (d<smallOdd)
smallOdd=d;}
cout<<"Enter a number: ";
cin>>e;
if (e%2==0){
if (e<smallEven)
smallEven=e;}
else if (e%2== 1 || e%2== -1){
if (e<smallOdd)
smallOdd=e;}
cout<<"Enter a number: ";
cin>>f;
if (f%2==0){
if (f<smallEven)
smallEven=f;}
else if (f%2== 1 || f%2== -1){
if (f<smallOdd)
smallOdd=f;}
【问题讨论】:
-
不要一遍又一遍地重复相同的代码,而是创建一个执行重复代码的函数。
-
教授希望我们只使用我们在课堂上学到的东西,这意味着没有函数也没有循环
-
您应该了解如何使用调试器。它将允许您暂停程序执行并执行诸如查看存储在变量中的值之类的操作。搜索教程或获取某种 C++ 书籍。这里不是让别人为你调试程序的地方。
-
@edmonda7 你是 YAIT 的受害者。
-
什么?没有功能?你认为
int main是什么?或者cin>>n是什么?这都是功能。学习没有函数的 C++ 就像学习在空中游泳一样。