multiply or dividing doesn't works correctly when the second number is negative - calculator

im trying to write windows 7s calculator but i have problems just in multiply and divide. here im writing the codes that are connected to multiply so you can get the reason.
double input1;
double input2;
double result;
string amalgar;
amalgar means + or - or * or /
private void button14_Click(object sender, EventArgs e)
{
input1 = Convert.ToDouble(textBox1.Text);
textBox1.Clear();
amalgar = "*";
}
it was for * button.
this is for negativation button :
private void button20_Click(object sender, EventArgs e)
{
input1 = Convert.ToDouble(textBox1.Text);
input1 = input1 * (-1);
textBox1.Text = input1.ToString();
}
and this is for equal button:
input2 = Convert.ToDouble(textBox1.Text);
if (amalgar == "*")
{
result = (input1 * input2);
textBox1.Text = Convert.ToString(result);
}
here is some examples for results:
2*6=12 Right
2*(-2)=4 Wrong
(-2)*2=-4 R
4*(-5)=25 W
8*(-7)=49 W
3*(-6)=36 W
8/2=4 R
8/(-2)=1 W
8/(-3)=1 W

It's because when you hit the negative button, you overwrite what you had in input1 with the negative of the contents of the textbox.
private void button20_Click(object sender, EventArgs e)
{
input1 = Convert.ToDouble(textBox1.Text); // These lines overwrite
input1 = input1 * (-1); // anything in input1
textBox1.Text = input1.ToString();
}
So that when you go to the equals code, input 2 and input 1 are always the same number if the last thing you pressed was the negative button.
input2 = Convert.ToDouble(textBox1.Text); // this equals input1 if the last thing
// you pressed was the negative button
if (amalgar == "*")
{ // ....
In button20_Click you need to modify the contents of textBox1 without overwriting input1. Something you could try is using a local variable to do all your calculations on:
double modifiedInput = Convert.ToDouble(textBox1.Text);
modifiedInput = modifiedInput * (-1);
textBox1.Text = modifiedInput.ToString();

i have solved it .it was an easy mistake.
the problem was in negativation button with i tried to multiply input1 by -1.
i have changed the code to :
input3 = Convert.ToDouble(textBox1.Text);
qarine = input3 * (-1);
textBox1.Text = qarine.ToString();
in that button and some clauses in equal button :
else if (amalgar == "*")
{
if (input1 > 0 && input2 > 0)
{
result = (input1 * input2);
}
else if (input1 < 0 && input2 < 0)
{
result = (input1 * input2);
}
else if (input1 < 0 && input2 > 0)
{
result = (qarine * input2);
}
else if (input1 > 0 && input2 < 0)
{
result = (input1 * qarine);
}
textBox1.Text = Convert.ToString(result);
}

Related

How to move the character in a certain way?

There is a way. The character starts at the midpoint. Then it should move to the right, if HorizontalAxis > 0 and to the left, if < 0. I have did something like this -
Way:
public Transform[] PatrolPoints;
public Transform Way;
public int CurrentPoint;
public int NeedPoint;
if (transform.position == PatrolPoints[CurrentPoint].position && CurrentPoint < PatrolPoints.Length-1)
{
//PatrolPoints[CurrentPoint];
NeedPoint = CurrentPoint + 1;
}
else if(transform.position == PatrolPoints[NeedPoint].position && CurrentPoint != PatrolPoints.Length - 1)
{
CurrentPoint++;
}
else if(transform.position == PatrolPoints[PatrolPoints.Length - 1].position)
{
NeedPoint--;
}
if (CurrentPoint != PatrolPoints.Length - 1 && moveAxis > 0)
{
transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NeedPoint].position, moveAxis * moveRate * Time.deltaTime);
//An error occurs here
}
else if(CurrentPoint > 0 && moveAxis < 0)
{
transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NeedPoint - 1].position, -moveAxis * moveRate * Time.deltaTime);
}
Length of the array - 3 elements.
From the middle point to the right, the character normally goes both left and right, but as soon as I get to the last point, an error occurs -
Array index is out of range
During the error variables are:
NeedPoint: -1;
CurrnetPoint: 2;
And from the middle to the left point the character does not go at all.
this is the solution for:
The character starts at the midpoint. Then it should move to the
right, if HorizontalAxis > 0 and to the left, if < 0.
i assumed that "move to the right" means increasing the index in array and "move to the left" means decreasing the index in array
public Transform[] PatrolPoints;
public int NextPointOnLeft = 0; // because player starts at 1
public int NextPointOnRight = 2; // because player starts at 1
if (HorizontalAxis < 0)
{
if (transform.position == PatrolPoints[NextPointOnLeft].position)
{
if(NextPointOnLeft > 0)
{
--NextPointOnLeft;
}
// EDIT: NextPointOnRight = NextPointOnLeft + 1;
}
// EDIT:
NextPointOnRight = NextPointOnLeft + 1;
transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NextPointOnLeft].position, moveRate * Time.deltaTime);
}
if (HorizontalAxis > 0)
{
if (transform.position == PatrolPoints[NextPointOnRight].position)
{
if(NextPointOnRight < PatrolPoints.Length-1)
{
++NextPointOnRight;
}
// EDIT: NextPointOnLeft = NextPointOnRight - 1;
}
// EDIT:
NextPointOnLeft = NextPointOnRight - 1;
transform.position = Vector3.MoveTowards(transform.position, PatrolPoints[NextPointOnRight].position, moveRate * Time.deltaTime);
}
if you need a different solution, please specify what you need

mergsort printing a strange result

I am having an issue with my merge sort, when I print out my sortedArray it only returns [ 0.0, 0.0.....] Im not sure if there is an error in my sort code or in my print line or if it has to do with doubles. The code I am us posted below.
By calling System.out.println(toString(sortedArray) I get an even more obscure answer.
Thanks for any help.
package mergesort;
import java.util.Arrays;
import java.util.Random;
public class mergesort {
public static void main(String[] args) {
double[] array = getIntArray();
long before = System.nanoTime();
double[] sortedArray= mergeSort(array);
System.out.println("Sorting took "+ (System.nanoTime() - before) +" nanoseconds ");
System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");
}
private static String toString(double[] array) {
StringBuilder sb = new StringBuilder("[ ");
double len = array.length;
for(int i = 0; i < len - 1; i++) {
sb.append(array[i] + ", ");
}
sb.append(array[(int) (len - 1)] + " ]");
return sb.toString();
}
public static double[] mergeSort(double[] array) {
if (array.length <= 1) {
return array;
}
int half = array.length / 2;
return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
mergeSort(Arrays.copyOfRange(array, half, array.length)));
}
private static double[] merge(double[] ds, double[] ds2) {
int len1 = ds.length, len2 = ds2.length;
int totalLength = len1 + len2;
double[] result = new double[totalLength];
int counterForLeft =0,counterForRight=0,resultIndex=0;
while(counterForLeft<len1 || counterForRight < len2){
if(counterForLeft<len1 && counterForRight < len2){
if(ds[counterForLeft]<= ds2[counterForRight]){
result[resultIndex++] =(int) ds[counterForLeft++];
} else {
result[resultIndex++] =(int) ds2[counterForRight++];
}
}else if(counterForLeft<len1){
result[resultIndex++] = (int) ds[counterForLeft++];
}else if (counterForRight <len2){
result[resultIndex++] =(int) ds2[counterForRight++];
}
}
return result;
}
private static double[] getIntArray() {
double[] array = new double[10000];
Random random = new Random();
for(int i = 0; i < 10000; i++) {
array[i] = (random.nextDouble() * .99999);
}
return array;
}
}
In the merge method, when copying from one of the input arrays to the results, you cast to int. For example:
result[resultIndex++] =(int) ds[counterForLeft++];
All your doubles are in the range [0...1), so the result of casting any of them to int is zero. Just get rid of those casts, and you will keep your numbers in the merge result.
As an additional tip, it is much easier to debug small problems than large ones. It failed for any size greater than 2, so you should have been debugging with size 2, not 10000.

Overloading Operator Rational Error

So I have looked around because this seems to be a common homework problem for most C++ students, but I can't seem to find one that will answer my issue. I feel that I have filled out the code correctly but I get the same error each time.
Here is my code:
#include <iostream>
using namespace std;
class Rational
{
public:
Rational() {
num = 0;
denom = 1;
};
Rational(int n, int d) {
num = n;
denom = d;
normalize();
}
Rational(int n) {
num = n;
denom = 1;
}
int get_numerator() const {
return num;
}
int get_denominator() const {
return denom;
}
void normalize() {
if ((num > 0 && denom < 0)||(num < 0 && denom < 0)) {
num = -1 * num;
denom = -1 * denom;
}
int gcdcheck = GCD(num,denom);
num = num / gcdcheck;
denom = denom / gcdcheck;
}
int Rational::GCD(int n, int d) {
int temp;
n = abs(n);
d = abs(d);
if (n > d) {
// Do nothing everything is where it should be
}
else {
temp = n;
n = d;
d = temp;
}
int factor = n % d;
while (factor != 0) {
factor = n % d;
d = n;
n = factor;
}
return d;//Return the value to normalize to simplify the fractions to simplist form
}
Rational operator+(Rational b) const {
Rational add;
//Addition of fractions (a*d/b*d + c*b/d*b)
//Numerator = (a*d + c*b)
add.get_numerator = b.get_numerator * denom + b.get_denominator * num;
//Denomenator = (b*d)
add.get_denominator = b.get_denominator * denom;
add.normalize();
return add;
}
Rational operator-(Rational b) const {
Rational sub;
//Same as Addition just a minus sign
//Numerator = (a*d + c*b)
sub.get_numerator = b.get_numerator * denom + b.get_denominator * num;
//Denomenator = (b*d)
sub.get_denominator = b.get_denominator * denom;
sub.normalize();
return sub;
}
Rational operator*(Rational b) const {
//Multiply the numerators and denomenators
Rational multi;
multi.get_numerator = b.get_numerator * num;
multi.get_denominator = b.get_denominator * denom;
multi.normalize();
return multi;
}
Rational operator/(Rational b) const {
//Division of fractions is done by the recipricol of one of the fractions
Rational divi;
divi.get_numerator = b.get_numerator * denom;
divi.get_denominator = b.get_denominator * num;
divi.normalize();
return divi;
}
//To avoid issues with rounding the compare functions will multiply instead to give clean whole numbers
//This will be done by multiplying the denomenators by the opposite numerator
bool operator==(Rational b) const {
return ((b.get_numerator * denom == b.get_denominator * num));
}
bool operator<(Rational b) const {
return ((b.get_numerator * denom > b.get_denominator * num));
}
double toDecimal() const {
double result;
result = static_cast<double> (num)/ static_cast<double> (denom);
return result;
}
private:
int num = 0; // default value is 0
int denom = 1; // default value is 1
};
ostream& operator<<(std::ostream& output, Rational& a) {
if (a.get_denominator == 0) {
output << "Divide by Zero";
}
output << a.get_numerator << '/' << a.get_denominator;
return output;
}
I know its a lot of code and I don't expect someone to go through it all debugging I just thought I would post it all just in case the problem spans farther then where I think the issue is.
I get the same errors for each operator:
1: error C3867: 'Rational::get_denominator': non-standard syntax; use '&' to create a pointer to member
2: '*': error C3867: 'Rational::get_denominator': non-standard syntax; use '&' to create a pointer to member
3: error C3867: 'Rational::get_numerator': non-standard syntax; use '&' to create a pointer to member
I have looked at code from different online sites that have done this problem and tried their methods but it doesn't seem to work. I have added const and & to the parameters in the functions and I still get the same issues. Am I calling a function incorrectly or initializing one wrong?
You have multiple problems in the code. Here is the corrected code.
you were returning a value not a reference.
when you are defining a function inside the class you dont need to specify the full name
the () for function calls were missing
There are some comments on the code at the end.
#include <iostream>
#include <cmath>
using namespace std;
class Rational
{
public:
Rational()
{
num = 0;
denom = 1;
};
Rational(int n, int d)
{`
num = n;
denom = d;
normalize();
}
Rational(int n)
{
num = n;
denom = 1;
}
int& get_numerator()
{
return num;
}
int& get_denominator()
{
return denom;
}
void normalize()
{
if ((num > 0 && denom < 0) || (num < 0 && denom < 0))
{
num = -1 * num;
denom = -1 * denom;
}
int gcdcheck = GCD(num, denom);
num = num / gcdcheck;
denom = denom / gcdcheck;
}
int GCD(int n, int d)
{
int temp;
n = abs(n);
d = abs(d);
if (n > d)
{
// Do nothing everything is where it should be
}
else
{
temp = n;
n = d;
d = temp;
}
int factor = n % d;
while (factor != 0)
{
factor = n % d;
d = n;
n = factor;
}
return d;//Return the value to normalize to simplify the fractions to simplist form
}
Rational operator+(Rational b) const
{
Rational add;
//Addition of fractions (a*d/b*d + c*b/d*b)
//Numerator = (a*d + c*b)
add.get_numerator()= b.get_numerator() * denom + b.get_denominator() * num;
//Denomenator = (b*d)
add.get_denominator() = b.get_denominator() * denom;
add.normalize();
return add;
}
Rational operator-(Rational b) const
{
Rational sub;
//Same as Addition just a minus sign
//Numerator = (a*d + c*b)
sub.get_numerator() = b.get_numerator() * denom + b.get_denominator() * num;
//Denomenator = (b*d)
sub.get_denominator() = b.get_denominator() * denom;
sub.normalize();
return sub;
}
Rational operator*(Rational b) const
{
//Multiply the numerators and denomenators
Rational multi;
multi.get_numerator() = b.get_numerator() * num;
multi.get_denominator() = b.get_denominator() * denom;
multi.normalize();
return multi;
}
Rational operator/(Rational b) const
{
//Division of fractions is done by the recipricol of one of the fractions
Rational divi;
divi.get_numerator() = b.get_numerator() * denom;
divi.get_denominator() = b.get_denominator() * num;
divi.normalize();
return divi;
}
//To avoid issues with rounding the compare functions will multiply instead to give clean whole numbers
//This will be done by multiplying the denomenators by the opposite numerator
bool operator==(Rational b) const
{
return ((b.get_numerator() * denom == b.get_denominator() * num));
}
bool operator<(Rational b) const
{
return ((b.get_numerator() * denom > b.get_denominator() * num));
}
double toDecimal() const
{
double result;
result = static_cast<double> (num) / static_cast<double> (denom);
return result;
}
private:
int num = 0; // default value is 0
int denom = 1; // default value is 1
};
ostream& operator<<(std::ostream& output, Rational& a)
{
if (a.get_denominator() == 0)
{
output << "Divide by Zero";
}
output << a.get_numerator() << '/' << a.get_denominator();
return output;
}
Some comments on the code... Returning a reference, especially to a private member is really bad. I suggest you to create a set function.
so basically keep the get function as before
int get_denominator() const
{
return denom;
}
and create a new function to set value
int set_denominator(int in)
{
denom = in;
}
You try to call the function without the parethesis. It should be get_denominator()
Without the parenthesis you get the pointer to the function instead and try to perform an arythmetic on it - hence the error.

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}

How to show 1 label box at a time

I sm very new to C#~ as you will soon see. I am trying to make a for that allows me to enter a gpa and a test score. I have two label boxes, one says you are accepected if you meet the criteria and the other says rejected. How can I make just one label box show up when it is called? This is what I have done so far.
private void button1_Click(object sender, EventArgs e)
{
const double lowestGPA = 3.0;
const int lowestTest = 60;
const int highestTest = 80;
double gpa;
double test;
test = Convert.ToDouble(textBox2.Text);
gpa = Convert.ToDouble(textBox1.Text);
label3.Visible = true;
if ((gpa > lowestGPA) && (test > lowestTest))
label3.Text = "Accepted!";
else
label4.Text = "Rejected!";
if ((gpa < lowestGPA) && (test > highestTest))
label3.Text = ("Accepected!");
else
label4.Text = "Rejected!";
}
im not sure that I understand but I would do it like this
if (((gpa > lowestGPA) && (test > lowestTest)) || ((gpa < lowestGPA) && (test > highestTest)))
label3.Text = "Accepted!";
else
label3.Text = "Rejected!";