2015-02-09 38 views
-3

我正在为一个开始的C++类进行家庭作业分配,并且我有点失落。
这是作业:如果初始输入是C++中的奇数整数,则将两个整数相乘

创建一个C++程序,要求用户输入一个数字。

该程序的输出应该是以下之一: 您输入了一个偶数。 或 您输入了一个奇数。

如果用户输入一个ODD号码,请他们输入另一个号码。 将此编号乘以第一个编号并输出结果。

偶数/奇数部分非常简单 - 我得到了这部分工作。第二部分我完全失去了。我遇到了很多错误,我甚至无法弄清楚起点在哪里。如果有人可以给我一个暗示我做错了什么,我会非常感激。

#include <iostream> 
using namespace std; 

int main() { 
     int num1; // This is the original number entered by the user. 
     int num2; // This is the second number entered if the first number is odd. 
     cout << "Enter a number: "<< endl; 
     cin >> num1 >> endl; 
     if (num1 % 2 == 0) { 
       cout << num << " Your number is even." << endl; 
}  if (num1 % 2 != 0) { 
       cout << num1 << " Your number is odd. Please enter another number: “<< endl; 
       cin >> num1 >> endl; 
     } // end of if odd 
     cout << " Your two numbers multiplied equals (num1 *= num2)” << endl; 

} // end of main() 
+4

你问第二个数字,然后做:'cin >> num1 >> endl;'不应该在'num2'中?你也说你得到很多错误,但实际上并没有告诉我们这些错误是什么。 (PS:'cout << num'这是无效的,你没有声明'num'作为一个变量) – Borgleader 2015-02-09 21:32:57

+0

你应该记得从'main'返回一个值(而不是让控制权流走)。 – inetknght 2015-02-09 21:34:56

+0

我认为语法高亮显得很明显,你在那里有一些流浪的智能引号。 'cin >> endl;'应该消失。 @inetknght,当流出'main'的末尾时返回0。 – chris 2015-02-09 21:35:47

回答

0

为奇数值

if (num1 % 2 != 0) { 
    cout << num1 << " Your number is odd. Please enter another number: “<< endl; 
    cin >> num2 >> endl; 
    cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl; 
      } 
+0

我看到的唯一变化是'num1'没有被赋值乘法的结果,这是好的,但是没有可观察到的差别。 – chris 2015-02-09 21:37:04

+0

但该代码正在计算num1 * num2。 OPs代码没有。所以这是一个改进:) – moobi 2015-02-09 21:39:45

+0

是的,我确实错过了输入中的s/num1/num2 /。突出显示改变的内容通常是一个好主意,这就是一个很好的例子。 – chris 2015-02-09 21:41:14

2
#include <iostream> 
using namespace std; 

int main() { 
    int num1; // This is the original number entered by the user. 
    int num2; // This is the second number entered if the first number is odd. 
    cout << "Enter a number: "<< endl; 
    cin >> num1; 
    if (num1 % 2 == 0) { 
     cout << num1 << " Your number is even." << endl; 
    }  
    else { 
     cout << num1 << " Your number is odd. Please enter another number: " << endl; 
     cin >> num2; 
     cout << " Your two numbers multiplied equals " << num1*num2 << endl; 
    } // end of if odd 
    return 0;   
} // end of main() 

该部分下面是固定的代码。您试图cout << num,但没有num变量,应该是num1,也是cin >> endl错误。

什么是意想不到的,你的最后不是"但是别的,它会产生很多错误。

0

更正

if (num1 % 2 != 0) { 
cout << num1 << " Your number is odd. Please enter another number:"<< endl; 
cin >> num2; 
cout << " Your two numbers multiplied equals:" << (num1 * num2) << endl; 
} 

后不要放置quotaion标记之间的公式。这将它们变成字符串或字符,不能像愿望一样执行。即cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;

将语句cout << " Your two numbers multiplied equals (num1 *= num2)” << endl;置于if语句的外侧,即使该语句不是奇数,也会导致语句运行。这不符合任务。和num2为空仍然会导致错误