Warum funktioniert der Code nicht korrekt? (blutiger Anfänger)
-
#include <iostream>
using namespace std;int main ()
{
int input;
cout << "For addition, enter number 1:\n ";
cout << "For substraction, enter number 2:\n ";
cout << "For multiplication, enter number 3:\n ";
cout << "For division, enter number 4:\n\n ";cin >> input;
//addition
if (input = 1)
{
int a, b;
cout << "Enter your first number: ";
cin >> a;cout << "Enter your 2nd number: "; cin >> b; int sum = a + b; cout << "Your number is " << sum << endl; return 0; }
//substraction
else if (input = 2)
{
int c, d;
cout << "Enter your first number: ";
cin >> c;cout << "Enter your 2nd number: "; cin >> d; int sum1 = c - d; cout << "Your number is " << sum1 << endl; return 0; }
//multiplication
else if (input = 3)
{
int e, f;
cout << "Enter your first number: ";
cin >> e;cout << "Enter your 2nd number: "; cin >> f; int sum2 = e * f; cout << "Your number is " << sum2 << endl; return 0; }
//division
else if (input = 4)
{
int g, h;
cout << "Enter your first number: ";
cin >> g;cout << "Enter your 2nd number: "; cin >> h; int sum3 = g / h; cout << "Your number is " << sum3 << endl; return 0; }
return 0;
}
-
Eine Zuweisung ist kein Vergleich und in jedem if Statement verlässt Du das Programm über
return 0
.
-
@zeropage sagte in Warum funktioniert der Code nicht korrekt? (blutiger Anfänger):
Eine Zuweisung ist kein Vergleich
Korrekt - das weiß aber sogar der Compiler.
Also @Azrael: schalte Warnungen beim Compilieren immer ein! Der Compiler wird dich auf viele Dinge, die womöglich falsch sind, hinweisen. Bei gcc & clang nutzt du bitte mindestens
-Wall
und-Wextra
, bei MSVC/W4
.Clang sagt dir dann zum Beispiel:
<source>:15:11: warning: using the result of an assignment as a condition without parentheses [-Wparentheses] if (input = 1) ~~~~~~^~~ <source>:15:11: note: place parentheses around the assignment to silence this warning if (input = 1) ^ ( ) <source>:15:11: note: use '==' to turn this assignment into an equality comparison if (input = 1) ^ ==
D.h. sogar der Lösungsvorschlag wird in diesem Fall gleich mitgeliefert! Beachte immer alle Warnungen und behebe die Ursachen für die Warnungen.
-
@wob Ah top, vielen lieben Dank!