C++ :: How Sub String And Math Can Be Used To Make Logical Decisions

Dec 1, 2014

This is an example of how sub string and math can be used to make logical decisions without using if/elses or switches. It works because of this equation

(x + |x|)/x = 2 if x > 0 and = 2 if x < 0.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
//declaration of variables

[Code] ....

View 1 Replies


ADVERTISEMENT

C/C++ :: Binomial Expansion - Simple Math String Into Array

May 5, 2014

My project is binomial expansion. I want to allow for basic string input. Then, I must process the string for input into the other portions of my program. To make the binomial expansion calculation simpler I am using two separate arrays for the first and second term of the binomial expansion. The integer array structure for each term is [{numerical Coefficient of term}, {exponent of variable a}, {exponent of variable b}, {exponent of variable c}, ......{exponent of variable x}, {exponent of variable y}, exponent of variable z}].

So, if the user doesn't use a variable it's exponent's value will = 0. The reason why I set my array up like this is so it would be very simple to raise each term to the power of n, or (n-k) (Multiple variable exponents by number, raise #coefficient to the power). It would also be easy to combine the terms to get one term. terms[0] are multiplied, all other terms are added.

My issue is translating a basic mathematical string consisting of only Integers, letter, parenthesis, and '^', into the array. I find difficulty mainly due to the '^' symbol. I know how to find the array index for a given letter. termArrayIndex = (int)((char from string) - 'a' + 1)

the main things causing me issues

-The issue is knowing which numbers to multiply by the array.

E.g. (_(_____)^#(__^#__)^#____)^#

I started by finding the first ')', then finding the preceding '(' and processing that string. I would then remove said string and use recusrion to go through the whole string. This method doesn't work because there is data loss upon removal of processed string. EG (__(__)^#) =remove innermost string and parenthesis=> (__^#) != (__()^2,

-maybe enter all terms, leave parenthesis, then process exponents separately...

-I may be able to find the # of separate terms by seeing # of times a '(' comes after a ')'

This is by far the most difficult part of the problem for me. But that also makes it the most fun. I want it to be able to handle all variation of these basic mathematical expressions.

View 3 Replies View Related

C :: Make A String Out Of Part Of A String

Dec 9, 2013

I have a string that contains a various number of lines which are each separated by and so what I want to do is to put each line into a node in a linked list.The relevant sections in my code are as follows:

Code:

typedef struct line *Line;
struct line {
char *text;
int lineNum;
Line next;
}

[code]....

Code:

strncpy(curr->text, text[prevPos], subLength);

With this line, I was hoping to make curr->text a string that is length subLength and begins at position prevPos in the text string. Except text[prevPos] is treated as a single character and not a string that begins at that position.

View 8 Replies View Related

C++ :: Using Logical Operators Like And Or

Dec 20, 2013

I wrote this program using an online compiler i am getting a lot of errors.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string birthmonth;
string birthday;

[Code] ....

View 6 Replies View Related

C :: Seg Fault Using Logical OR On For Loop

Mar 9, 2013

I've received a segmentation fault in this part of code:

Code:
for (; str[i] != '' || str[i] != ' '; i++) {
result[result_pos] = str[i];
result_pos++;
}

which, should mean:

Code: If str[i] is not equal to NULL character nor ' '; then, keep printing the chars within the word to variable result.

To understand what the function does, here's the whole code:

static char result[999];
/* char *split_word(const char *str, long n);
* Splits a string word-by-word. Where N is the word number. */
char *split_word(const char *str, long n) {

[Code]....

I'm trying to accomplish an easier way round to split string by word than using "strtok_r()". It might sound like "re-inventing the wheel", but... i will try to make it neat later.

The code looks okay, why would it segfault?

View 7 Replies View Related

C++ :: Casting A Logical Boolean As Int?

Jun 8, 2013

Let's say I have a product that needs service after 500 hours at 100 RPM. I can dsiplay the remaining hours only as an integer and we only have integer math. Management wants it to display 500 for the first hour, not 499 after the first minute is ticked off. But after a few minutes fullHours will be 499 and partialHours will have some value. I have 3 ways to determine displayHours to suit management and I want to know if the first is ligit.

short fullHours = 500;
short partialHours = 0;
short displayedHours = 0;

// Method 1 - Is is Kosher to cast a boolean as an int? Is TRUE always a 1 or is that a bad assumption?

displayedHours = fullHours + (short) (partialHours != 0);

//Method 2 - Works but some have disdain for the ternary conditional

displayHours = fullHours + (partialHours ? 1 : 0);

//Method 3 - seems a bit pedantic

displayHours = fullHours;
if (partialHours != 0) {
displayHours++;
}

View 19 Replies View Related

C++ :: Next Permutation Logical Error

May 11, 2013

I wrote this code to solve a problem in which the user inputs a permutation of size 'N' and the next permutation of the same elements has to be generated.

I went about this in this way: given 3 2 5 4 1, starting from the right, the first no. has to be searched which has a no. greater to it on its right. Here it is 2. Now an array is generated containing all no.s on its right and greater than it. For 2, it is: 5,4. Out of these the smallest member is searched for and switched with 2. So, 4 is switched with 2 to get the Next Permutation: 3 4 5 2 1.

The code I wrote does not show any error but does not return the correct value when run and gives the same value instead. If I enter '3 2 5 4 1' it returns the same value as the answer.

#include<iostream.h>
#include<conio.h>
void main() {
clrscr();
int N,M,i,n,c,swap,flag,count,small,m;
int Array[100],Key[100];

[Code] .....

View 2 Replies View Related

C++ :: Logical Operations Not Working?

Oct 7, 2014

int main()
{
char rORc, choice;
int sizerc;

[Code]....

when I input the character which is the underscore, and the row # it should display the table and sort that specific row. Why is the if statement skipped? This is not the complete program but has everything needed.

View 2 Replies View Related

C++ :: Online Shop - Serious Logical Error

Nov 15, 2013

My project is on an online shop in which you can manage a shop(adding ,deleting ,clearing and modifying items) also you can switch to different shops(all shops are same)

Code:
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

[Code] ....

The logical problem is serious because i am not able to find the error!!! There is some problem with display lines in void shop()-->if(mode=='s') and if(mode=='d'). I add only one item but in output screen i see two items(sometimes >2)
*note* to run the above display lines in the output screen....first register--->add atleast one item--->see your shop

View 12 Replies View Related

C/C++ :: Multiply 2 Variables That Go From 0 To 7 - Logical Operators?

Apr 9, 2015

#include <iostream>
using namespace std;
int main(){
int polje[8][8];{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++) {

[Code] .....

I don't get any errors,the program works. The problem is that it doesnt work how it should. This is a simple program that multiplies 2 variables(i and j)that go from 0 to 7. The problem I have is with the logical operators,i want the program to skip multiplication with 0 and when the 2 variables are the same value. When i try using only 1 logical operator it work.

View 2 Replies View Related

C++ :: Evaluating Logical Boolean Expressions

Jan 10, 2013

I am looking for a library to aid me in evaluating Boolean expressions. For example, i have an expression like this:

(1*(5+3)+9*65/5-(354*4565*5643+98) >= 12345) && ( 654*987+123 || (2345 > 23423 && 1 != 2)))

(It can also be much longer!) and would like to evaluate them to a true/false boolean.

There are tons of libraries to calculate the (numerical) result of a mathematical expression, but this is not what i want to do.

View 5 Replies View Related

C++ :: Logical Error In Output Of DAYNAME

Oct 31, 2014

I have to write a program that does the following: Monkey Business A local zoo wants to keep track of how many pounds of food each of its three monkeys eats each day during a typical week. Write a program that stores this information in a two-dimensional 3 - 7 array , where each row represents a different monkey and each column represents a different day of the week. The monkeys are represented by integers 1, 2, and 3; the weekdays are "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday". The program should first prompt the user to input the data for each monkey, starting with "Sunday" for monkey #1, then monkeys #2 and #3, followed by "Monday" for monkey #1, then monkeys #2 and #3 and so on, through "Saturday". The program then creates a report that includes the following information, each properly labeled (see below):

-Average amount of food eaten per day by the whole family of monkeys.
-The least amount of food eaten during the week by any one monkey.
-The greatest amount of food eaten during the week by any one monkey.

Input Validation: Do not accept negative numbers for pounds of food eaten. When a negative value is entered, the program outputs "invalid (negative) food quantity -- re-enter" and attempts to reread the value . Prompts And Output Labels: Decimal values should be displayed using default precision, i.e. do not specify precision. Each item read should be prompted for by a string of the form "Enter the food eaten by monkey #N on DAY:" when N is 1 or 2 or 3 and DAY is "Sunday" or "Monday" or ... or "Saturday".

The output should be of the form:

Average food consumed daily: 6.23
The least daily food consumed was by Monkey #0 on Friday
The most daily food consumed was by Monkey #2 on Sunday where the specific amount of food or specific monkeys or specific days identified depend on the actual input.

However after the process of resolving the errors unable to convert to standard string and unresolved externals I now have a logical error that causes the output of the DAYNAME variable to output as what appears to be hex in the following picture:

How I can fix this and why it's casting them as this in the output.

My full code is as follows because I don't know exactly, which line of code is causing this to happen:

Code:
//
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// constants
const int MONKEYS = 3;
const int DAYS = 7;

[Code] .....

View 5 Replies View Related

C++ :: How To Make 2 Array (x / Y) String

Jun 9, 2013

I want to make 2 array(x,y) string , when i do

string temp[8][8]

but

cout << temp[3][4] does not work ....

View 3 Replies View Related

C :: How To Determine Whether A Logical Or Arithmetic Shift Is Performed

May 26, 2013

If input value was shifted to the right on bit level. How can I determine whether a logical or arithmetic shift is performed.

Code:
#include <stdio.h>
#include <stdlib.h>
void main ()

[Code]......

View 6 Replies View Related

C/C++ :: Make Program To Print Out String

Nov 24, 2014

I'm trying to make a program in C where the user enters a string and it prints a word for example (name) in lowercase then the same word again but in capitals and lowercase like this (NnAaMmEe).

my code is below;

#include<stdio.h>
#include<ctype.h>
int main()

[Code].....

View 1 Replies View Related

C :: Binary Game - Using Values With Some Basic Logical Operations

Apr 24, 2014

When things at work get overwhelming, it's not unusual for me to briefly "escape" by writing small programs simply for fun. A few days ago, I had an idea for a "binary game". I completed the first draft of it yesterday.

The idea is simple. The game uses 8-bit values. At the start of the game, a random "target" value is generated. The player is dealt a "hand" of seven values. The object is to use the values in your hand, along with some basic logical operations, to create the "target" value. While the idea is simple, the game itself can be quite difficult.

Here is an example of the output:

Code: --------------------
T: 1111 1100 (0xFC)
--------------------
0: 0000 0000 (0x00)
--------------------
1: 1100 1110 (0xCE)
2: 1010 0011 (0xA3)
3: 1100 0101 (0xC5)
4: 1011 1111 (0xBF)
5: 1010 1011 (0xAB)
6: 0001 1011 (0x1B)
7: 0001 1011 (0x1B)
--------------------

: Looking at the first column:
- 'T' is the "target" value
- '0' can be thought of as the "game board" - this is the value that needs to match the target value for a win
- '1' - '7' are the values in your "hand"

You can apply logic AND ('A'), OR ('O'), or XOR ('X') to a value in your hand with the value on the "game board". You are also allowed to apply logic to two values in your hand to create a new value for your hand. When a value from your hand is used, it is removed.

Some examples of the commands:

A30 --- apply logic AND to value #3 in your hand, and the "game board" value
O23 --- apply logic OR to value #2 in your hand and value #3 in your hand
X70 --- apply logic XOR to value #7 in your hand, and the "game board" value

You can also be dealt new values (as long as there's room in your hand) with the '+' command. 'H' or 'h' prints the help, and 'Q' or 'q' exits the game.

I haven't thoroughly tested it yet, since I just finished it a yesterday, but so far it looks good. The program itself uses only standard C.

I was dickering with the idea of supporting more logical operators (NOT, NAND, NOR, XNOR, shift), but I like the simplicity and resulting difficulty of the current implementation.

During initial testing, I realized it's possible to have doubles in your hand. Also, it's quite possible to be dealt the target value directly, which means that you could potentially win with one move, chance permitting. At first I thought about defending against these conditions, but came to the conclusion that it is fine as is - chances of an instant win are small, and if it does occur, would still be an enjoyable experience. Besides, if you're dealt the target value after the "game board" value has been modified.

Also, I did not allow a value of "zero" in the players hand. This was originally because I thought it would be of little use (though I've been reconsidering this). This also means that if two values in the hand are combined and result in zero, both values are removed and no new value is added. This was originally a bug, but I think I'll just reclassify it as a feature

So far, I found that the best strategy is to avoid modifying the "game board" value, and just play with the values in your hand. If you can get the target value in your hand, you just OR it with the "game board" and you're done.

View 2 Replies View Related

C++ :: Logical Error - Change Value Inside Void Statement

Jul 16, 2013

I've encountered a slight logical error in my code

/*
Lab06_pensionplans.cpp
Purpose :
- Create a simple financial application to calculate retirement plans
*/
#include <iostream>
#include <cstdlib>
using namespace std;
void displayMenu() {
system("cls");

[Code] ....

Look at case 2, which the user supposed to key in a new input, the problem is the value will never got into main function, I don't know what should I modify with the function.

Figured out I need to change the

void changeData(int startingAge, int numOfYears,
double lumpSumAmount, double yearlyAmount, double interestRate )

into

void changeData(int &startingAge, int &numOfYears,
double &lumpSumAmount, double &yearlyAmount, double &interestRate )

View 2 Replies View Related

C++ ::  make Program That Can Type String Into Another Window?

Apr 26, 2013

I am trying to make a program that can type a string into another window. I have gotten it to the point that it can type the string, just not correctly. It will type random numbers and not the given string. The key event uses ASCII code for the arguments, and I don't see anything wrong with my numbers. Here is the code I have so far.

#include "stdafx.h"
#include <iostream>
#include <windows.h>

[Code].....

View 2 Replies View Related

C :: How To Make String Array From Strings In Text File

Mar 24, 2013

I want to make a string array from strings in a text file. Itry to do this but i couldn't do, where is my mistake?

Code:

#include <stdio.h>
#include <stdlib.h>
int main(){
char cumle[100],*c,*dene[50];
FILE *input;
input=fopen("input.txt","r");

[Code]...

View 1 Replies View Related

C++ :: Determine Number Of Times Change Each Specific Character In String To Make It Palindrome

Feb 19, 2015

I'm trying to determine the number of times I have to change each specific character in a string to make it a palindrome. You can only change a character one at a time from the end.

Example: "abc" -> "abb" -> "aba" should print 2. "aba" will print 0 because it's already a palindrome. "abcd" -> "abcc" -> "abcb" -> "abca" -> "abba" will print 4 because it took 4 changes to make a palindrome.

I'm not too sure how to approach this - I figured out the case where if it's a palindrome (if reversed string is the same) then it'll print out a 0.

int main() {
int number;
cin >> number; //expecting a number for first line user input
for (int i = 0; i < number; i++) {
string str;

[Code] ....

View 1 Replies View Related

C :: How To Write Powers Without Using Math

Sep 22, 2014

How would one write 3^i without using .math? (i being numbers 0-9)

More specifically, this is what I have:

Code:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x, n, answer1, first;
x = 3;
n = 10;
first = 1;

[Code]....

And this is what I want it to produce:

1 0 1.0
3 1 0.333333343
9 2 0.111111112
27 3 0.037037037
81 4 0.012345679
243 5 0.004115226
729 6 0.001371742
2187 7 0.000457247
6561 8 0.000152416
19683 9 0.000050805

I believe I am only having troubles with the first column,

View 10 Replies View Related

C++ :: Inserting Math Functions From GUI

Feb 8, 2013

I have a problem with entering math functions in my Bisection method algorithm program. I just don't know how can I make the function that I enter in my GUI app to go from the GUI to the loop and find the root.As far as I googled I only find codes that you need to pre-enter a function in the double/float.

For example:I have a function f(x) = x^3 - cos(x) - x - 3; and I want to enter that function trough the GUI i made in c++..So this is the main code.

#include "bisection.h"
#include "ui_bisection.h"
#include <QFile>
#include <QString>
#include <math.h>
#include <algorithm>
bisection::bisection(QWidget *parent) :

[code]....

View 11 Replies View Related

C++ :: Math Formulas Using Variables?

Mar 21, 2013

Working on a program that converts infix to postfix math formulas. Ive successfully converted the infix to a postfix notation but now i am having trouble solving the equation from the postfix form. Im trying to set a result equal to three variables as shown below:

result = op1 ch op2;

where op1 and op2 are numbers and ch is the operator (+-*/) depending on what the user entered into a string. The error im getting is that it expected a ";" before postfix so clearly it doesn't understand what im trying to do. how to put the answer from op1 ch op2 into result.

View 4 Replies View Related

C/C++ :: Finding The Value Of Sin(x) Without Using Math Function

Apr 14, 2013

How can i solve a problem of sin(x) without using any math.h and only using my own declared function.

#include <stdio.h>
int fact (int a) {
    int i;
    int k = 1;
    for (i=1;i<=a;i++)

[Code] ....

View 3 Replies View Related

C :: Calculate Value Of Math Expression Using Strings

Nov 4, 2013

Here is my objective: Write a c program that calculates the value of a mathematical expression comprised of positive numbers and the operations "+" and "-" . Specifically, first prompt the user to input an expression, read itin as a string, and then print the value of the expression. You may assume that the expression does not contain spaces, maximumsize of the expression (including digits and operators) can be 20,and that all numbers are single digit numbers.

Note that, the digits would be read in as characters; you will need to translate them to numbers (recall the ASCII table). Implementation Requirements:

Write a function called "evaluate" that takes as input a mathematical expression(as a string) and returns the value of the expression. The prototype of the function is: intevaluate(char expr[]);

Sample Output:
Input: 4+2-1+7 Output:12

Code:
int main()
{
char expr[21];
int a,ssum;
printf("Input: ");
scanf("%20s", expr);

[Code] .....

the program runs, but the output is not coming out correct.

View 11 Replies View Related

C :: Trapezoidal Rule - Math Library

Mar 22, 2013

I am new to c programing and I had spend 2 days on a program and I can't fix the error:

Code] ....
gcc Test.c -o Test.exe
/tmp/ccZkbk0V.o: In function `f':
Test.c:(.text+0x2f): undefined reference to `sqrt'
collect2: ld returned 1 exit status

Tthe program I am working in is:

#include <stdio.h>
#include <math.h>
int f(int x){
return (sqrt(4.0 - x*x));

[Code] .....

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved