You can use std::to_string to create a std::string from your int value. for (int i = 0; i <= 10; i++) { std::cout << "Image" + std::to_string(i+1) + ".png"; } Although in this case you might as well just use the stream operator<< for (int i = 0; i <=...
The float val is stored as 307.02999 or something like that intval just truncate the number, no rounding, hence 30702.
Okay here is the working code - thanks to @mireke for help // delay before playing var lower : UInt32 = 1 var upper : UInt32 = 6 var delayTime = arc4random_uniform(upper - lower) + lower var delayTimer = Double(delayTime) / 10 var delay = delayTimer * Double(NSEC_PER_SEC) var time...
ios,objective-c,arrays,object,int
you can use lastObject method to get last object from array int lastValue = [[yourArray lastObject] intValue]; ...
Here is your problem. char gender; scanf(" %s",&gender); gender is a char. That is, it only has memory for a 1 byte character. But you are using it as a string. You probably have the same problem for name1 since you are using & for that as well but can't...
use a dict mapping cards to values: Cards = {"1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, 'Jack': 10, 'Queen': 10, 'King': 10, 'Ace': 10} #Faces = Jack, Queen, King, Ace print('Welcome to Blackjack!\n\nHere are your cards: \n...
You are causing undefined behavior in scanf("%s", &c); because "%s" specifier adds a terminating nul byte to the target which is a single char. Instead you can try if (scanf(" %c", &c) != 1) handleErrorPlease(); the space before the "%c" is intentional, it will eat any white space character left...
java,casting,int,double,rounding
In all the outputs you printed (except the first one which is 0) Speed is smaller than 1 (7.026718463748694E-4, 5.27003884781152E-4, etc...). Notice the negative exponent. Therefore it's no wonder ceil returns 1....
You need to specify addExpense is a mutating function, like so: struct Expenses { var totalExpenses:Int = 0 mutating func addExpense(expense: Int) { totalExpenses += expense } } From the documentation: Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within...
This was extracted from the c11 draft n1570 6.5.4 Cast operators If the value of the expression is represented with greater range or precision than required by the type named by the cast (6.3.1.8), then the cast specifies a conversion even if the type of the expression is the same...
if you are sure that you are getting an int value in Selection Textview you can try this out: int b1 = Integer.parseInt(selection.getText().toString()); int b12 = b1 * 100; result.setText(String.valueOf(b12)); ...
Use cast_number/*char*/ = (char) help_variable_remove_pv + '0'/*int*/; instead of cast_number/*char*/ = (char) help_variable_remove_pv/*int*/; A character and an integer somewhat are different. This means that '0'(character 0) and integer 0 aren't equal. You'll have to add 48 (ASCII value of '0') to 0 to get the integer value of '0'. See...
From the C Standard, 6.3.1.8 Usual arithmetic conversions, emphasis mine: Many operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to determine a common real type for the operands and result. For the specified operands, each operand is converted,...
If you call ToString() on an array like that, you simply get the full name of the type of class. You could fix it a few ways. Print only the current item inside the loop, or print each item one at a time outside of the loop: Console.WriteLine("{0}{1}", item.PadRight(20), ticket1[0]);...
swift,core-data,int,type-conversion
The error is your ? after valueForKey. Int initializer doesnt accept optionals. By doing myUnit.valueForKey(“theNUMBER”)?.intValue! gives you an optional value and the ! at the end doesnt help it. Just replace with this: return Int(myUnit.valueForKey(“theNUMBER”)!.intValue) But you could also do like this if you want it to be fail safe:...
You're setting i too high. Consider the simplest case, where s has 1 digit. You want to multiply that digit by 1 (100), not 10 (101). So it should be: int i = lent(s) - 1; BTW, you shouldn't hard code the value 48, use '0': res += (c -...
This is because .length() (and .size()) return size_t, which is an unsigned int. You think you get a negative number, when in fact it underflows back to the maximum value for size_t (On my machine, this is 18446744073709551615). This means your for loop will loop through all the possible values...
In your C program, please replace: char intBufferCoupReq[20]; int data = recv(sock, intBufferCoupReq, 80, 0); printf("data recieved : %d\n",data); if( data == -1){ printf("Error while receiving Integer\n"); } With: char intBufferCoupReq[1024]; memset(intBufferCoupReq, '\0', sizeof(intBufferCoupReq)); int k = 0; while ( 1 ) { int nbytes = recv(sockfd, &intBufferCoupReq[k], 1, 0);...
For a pitch bend message data1 (your message.data[1]) is the LSB, and data2 (message.data[2]) is MSB. I'm not a C developer, but here's how I do it in some pseudo-code: (byte) data2 = pitchbend >> 7 (byte) data1 = pitchbend & 0x7F In English: MSB is: pitchbend bit shift right...
I made a test println() statement to print the value of c, and found that its value when BTLEserial.read() is 0000 turns out to be 48. Hardly surprising. The ASCII value of "0" is 48. The "int" that Adafruit_BLE_UART::read() returns is the most recent byte received; if you want...
Your problem is this line: B[0]=A[ilg-1] You're assigning an integer to B[0], which is not an iterable object. On your second iteration around the loop, you pass B[0] to the sum function, which attempts to iterate over it, throwing the exception....
One way to do this is to use the toFixed method off a Number combined with parseFloat. Eg, var number = 1501.0099999999999909; var truncated = parseFloat(number.toFixed(5)); console.log(truncated); toFixed takes in the number of decimal points it should be truncated to. To get the output you need, you would only need...
java,recursion,random,passwords,int
You're generating every combination of passwords because you're going through every value in your char array at each level of the recursive stack instead of picking a random value for the array. public static void main(String[] args) { Random rand = new Random(); int randomSize = rand.nextInt((13) + 8); String...
java,string,int,data-type-conversion
Here is a very simple example to process your file and split the string line and obtain the date object. public class FileReaderExample { public static void main(String[] args) { File file = new File("d:\\text.txt"); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; int lineNo = 1; while...
python,int,append,nested-lists
You can do it like this: data.append([int(x) for x in input().split()]) ...
java,string,arraylist,int,zero
The problem with your method is that, in your inner loop, you're removing zeroes regardless of its position in the list. There are multiple ways to achieve what you want. Here's one method using a single loop (without String or Collections operations that reverse your list for you): String nums...
You could do it manual unless using Math.pow do something like this public static long powerN(int number, int power) { int result = number; while(power > 0) { result*=number; power--; } return (long)result; } ...
Change printf ("The number of miles per gallon is:%d",dailyDrivingCost(a,b,c)); ^ to printf ("The number of miles per gallon is:%f",dailyDrivingCost(a,b,c)); d conversion specifier is used to print an int, to print a double (or a float) you need the f conversion specifier....
javascript,jquery,if-statement,click,int
You're thinking about click wrong. It means "When the button is clicked". It isn't a condition that you are testing for at the time the code runs. It is setting up an event handler to run later. So you need to rethink your test: if a button is clicked and...
The constructor for BitArray(bool[]) accepts the values in index order - and then CopyTo uses them in the traditional significance (so bitArray[0] is the least significant bit) - so your true, true, false, false ends up meaning 0011 in binary, not 1100. It's not ignoring the last two bits -...
interest is an int so this line interest / 100 is doing integer division, and will always be 0. The quick fix would be to change the literal so you are doing floating point math sum += sum*(interest / 100.0); ...
javascript,numbers,int,square,digit
function sq(n){ var nos = (n + '').split(''); var res=""; for(i in nos){ res+= parseInt(nos[i]) * parseInt(nos[i]); } return parseInt(res); } var result = sq(21); alert(result) ...
swift,int,character,swift-playground,swift2
In Swift 2.0, toInt(), etc., have been replaced with initializers. (In this case, Int(someString).) Because not all strings can be converted to ints, this initializer is failable, which means it returns an optional int (Int?) instead of just an Int. The best thing to do is unwrap this optional using...
python,variables,int,type-conversion
Imagine you had a function called func def func(): print("hello from func") return 7 If you then assigned func to x you are assigning the function itself to x not the result of the call x = func # note: no () x() # calls func() y = x() #...
c,gcc,int,printf,format-specifiers
There is no conversion. printf is not a function that accepts a float. It is a function that accepts an argument list that could be of any type. The compiler assumes that a float was given and you are seeing basically undefined behaviour. There is no mechanism that will parse...
The challenge is to realize you have a string of hex and a string of decimal, meaning you have a character string representation of the values, not the values themselves. So you will need to convert the string representations to the appropriate numeric values before converting back to the original...
Welcome to Stack Overflow Noctifer. While using PrintWriter class, you need to ensure that you flush and close it so that it releases all its resources, as it is not automatically flushed. In your code right now, since it is not closed so the changes are not being saved. The...
trunc function will truncate number to given number of decimals: select trunc(2.7, 0); trunc ------- 2 (1 row) ...
ios,objective-c,int,appdelegate
// AppDelegate.h @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (nonatomic) int myIntVariable; @end // ViewController.m #import "AppDelegate.h" - (void)viewDidLoad { [super viewDidLoad]; AppDelegate *delegate = [UIApplication sharedApplication].delegate; delegate.myIntVariable = 4; NSLog(@"%d", delegate.myIntVariable); } ...
java,android,integer,int,compare
This is because you are not using the primitive int type. You are using the reference Integer type. Your getPosition() method returns Integer. While comparing two reference with == operator it's actually compare it's reference not it's value. If you want to check whether two object are meaningfully equals then...
i is declared in main, private final int VERSION is outside of main. Move it inside main or declare i as a global. static int i=0; public static void main(String[] args) { String strFilePath = "./version.txt"; try { FileInputStream fin = new FileInputStream(strFilePath); DataInputStream din = new DataInputStream(fin); i =...
swift,int,uiinterfaceorientation,swift2,xcode7
Try like this override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if visibleViewController is KINWebBrowserViewController { return UIInterfaceOrientationMask.All } return UIInterfaceOrientationMask.Portrait } ...
I found the problem and the solution reading the comments :) The problem: I was retrieving data from a webservice via curl and json_encoding the result. At this point, json_encode converts bigints into floats. I solved it passing JSON_BIGINT_AS_STRING argument to json_encode. It's documented in PHP documentation: http://php.net/manual/es/function.json-decode.php...
The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. The type of the second operand must be an int or a type that has a predefined implicit numeric conversion to int.
In the Player class you need to put the override. Someting like: public class Player { // fields here @Override public String toString() { return Strength + " " + Defense; // plus all the fields here } } Regarding your other question: yes, you can, but since all the...
Each symbol has an numeric representation, so basically each char is a number. Here is the table of characters and its values. So, in your code name[1] = numbers[1];, you assign name[1] to 2, which is equal to symbol STX in the ASCII table above, which is not a printable...
c,sockets,int,unsigned-integer
The htonl function is declared in <arpa/inet.h>. Assuming you have a proper #include for that header: #include <arpa/inet.h>` the declaration uint32_t htonl(uint32_t hostlong); will be visible, so the compiler knows the expected argument type and the result type. If you want to pass the value 5 to the htonl function,...
c,arrays,segmentation-fault,initialization,int
In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...
java,netbeans,random,int,generated
This is how to make it generate a random number, I know it is longer but its much easier to understand. import java.util.Random; class (INSERTCLASSNAME){ public static void main(String[] args){ Random random = new Random(); int number; for(int counter=1; counter<=1;counter++){ number = 1+random.nextInt(100); System.out.println(number); } } } ...
int,lldb,arithmetic-expressions
po stands for print object, so it may be creating a pointer. Try e instead: e minutes * 60 + seconds
python,object,matrix,int,multiplication
You are treating m1 as a nested list of integers: result[i][j] += m1[i][k] * m2[k][j] # ^^^^^^^^ It is not; it is merely a simple list of integers. m1[i] then is an integer object and you cannot index integers: >>> [3, 4, 2][0] 3 >>> [3, 4, 2][0][0] Traceback (most...
What is s in the above program? Is it an int* or something else? s is an incomplete type. That's why you cannot sizeof it. As @BLUEPIXY suggests, it's initialized with zero because it's declared in global scope making a "tentative definition". int i[]; the array i still has...
You cannot create an array with run-time size, it must be known at compile time. I would recommend a std::vector instead. One solution would be to count the characters after converting to a string #include <string> int MyFunction(int number) { std::vector<int> myarr(std::to_string(number).size()); } Mathematically, you can take the log (base...
The short answer to your question is that the value printed is based on the type that the conditional expression evaluates to. So really your question boils down to, why does the type of the conditional expression differ between char y = 'y'; int i = 0; System.out.print(false ? i...
java,if-statement,while-loop,int,logic
Try setting min and min2 to Integer.MAX_VALUE. Practically this should solve your problem because the data type of integers you are working with is int. But theoretically, setting min and min2 to the first input value is the correct solution. EDIT: As a matter of fact, I see that you...
I think what you're trying to do is look up an object by name. You can't do it literally the way you have, but it's common and you don't have to add to much code. Let's say you have an RPG game and you have team members, which each little...
You should do some testing on this because I haven't run extensive tests but it has worked on the cases I've put it through. Also, it might be worth ensuring that each character in the string is truly a valid integer as this procedure would bomb given a non-integer character....
c,string,int,long-integer,strtol
We give the algorithm, you write the code. Agree? OK, so the logic should be create an array of chars based on the end-start+1 index range. do a memcpy() from the source to the new array fro the end-start size. null-terminate the array. use strtol() to convert the array to...
The error you got has nothing to do with the scope of buf. It refers to the system function which expects only one parameter: int system(const char *command) Hope I helped....
java,if-statement,multidimensional-array,int,paint
The first index in a 2D array is by convention the row index and the second is the column index, so your co-ordinates are the wrong way round: public void collisionChecker(int playerX, int playerY){ //takes the user's location and then checks if they are running into the wall if(mazeWalls[playerY /...
I'm not quire sure I understand the intention of returning a double or and int knowing that's not really possible for a single function to return different data types. What I think I understand from your sample code, is that if a String (For example, "123.0" doesn't matter how many...
Replace all the non-numbers with nothing, then with that number see if the original string contains it. String str = "foo1b2ar"; //starting string String num = str.replaceAll("[\\D]",""); //the number it contains return str.contains(num) && num.length() <= 2; //does the original have that number all together? and is it short? Example:...
Your command has an extra right parenthesis at the end. That is all that the error message is refering to.
c,floating-point,int,printf,format-specifiers
printf("%.2f", a/b); The output of the division is again of type int and not float. You are using wrong format specifier which will lead to undefined behavior. You need to have variables of type float to perform the operation you are doing. The right format specifier to print out int...
c,int,compare,type-conversion,unsigned-integer
Use wider integer math for the compare. No cast used, type of variables are not changed. An optimized compiler will not do a multiplication, just a integer widening. Could use a * 1LL or + 0LL instead int main(void) { long long ll = 1; unsigned int x = 5;...
If you are using java 8 then you can still use the same syntax LocalDateTime fiveMinutesLater = LocalDateTime.now().plusMinutes(5) ...
haskell,integer,int,type-conversion,tuples
There are two problems : first your code doesn't do what you think it does, second just converting the length to an integer is completely useless... 1) Your code is erroneous since maximum doesn't select the longest list. maximum works with Ord instances and select the greatest according to the...
c#,oracle,entity-framework,asp.net-web-api,int
OK, looks like this will work, for anyone else who may be having the same difficulties. If you're using the managed data access libraries from Oracle, add the following to your app/web.config: <oracle.manageddataaccess.client> <version number="*"> <edmMappings> <edmMapping dataType="number"> <add name="bool" precision="1" /> <add name="byte" precision="2" /> <add name="int16" precision="5" />...
Judging by this statment: where the user rolls 3 dice and gets some random outputs (up to integer 6). My next step is to add those 3 values obtained and get its sum I assume you want this: first initialize sumDice to 0: int sumDice=0; then, in every for loop...
you need to initialize your total variable in order to increase it. var total = 0; For accessing the div´s text, you have to get the innerHTML property, like str=value[x].innerHTML; Here´s a plunk with the example http://plnkr.co/edit/5S6cJDPbT7PvO0u77z8m?p=preview Hope you find it useful...
The base argument of the int class defaults to 10 int(x, base=10) -> integer leading zeroes will be stripped. See this example: In [1]: int('0777') Out[1]: 777 Specify base 8 explicitly, then the hex function will give you the desired result: In [2]: hex(int('0777', 8)) Out[2]: '0x1ff' ...
Since float can hold an integer but not vice versa. Just read the data like a float and check if it is an integer using something like if(ceilf(f) == f) { i=(int)f; } //Here i is an integer and f is the float you read using %f To see more...
You need to use raw_input for python2, input in python2 is basically eval(raw_input()) and as you have no variable okay defined you get the error. In [10]: prime = (str(input("\n"))) foo --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-10-15ff4b8b32ce> in <module>() ----> 1 prime = (str(input("\n"))) <string> in <module>() NameError:...
Change to: class MyClass { public: static const int MAJOR = 3; static const int MINOR = 3; static const int REV = 0; }; If these versions are constant. Otherwise as: class MyClass { public: static int MAJOR; static int MINOR; static int REV; }; Then somewhere in a...
drawRect in inherited from Graphics which uses int to specify the co-ords & size. The Graphics2D object on the other hand, is capable of dealing with graphics values that lie 'between whole pixels'. To compensate it will typically render a dithered pixel (part way between the drawing and BG color)...
Glib::ustring provides a format static function that simply forwards whatever you throw at it (up to 8 arguments, no variadic template yet it seems) to a stringstream and returns the formatted string: Glib::ustring text = Glib::ustring::format(123456); Since c++11 the standard library also has an overloaded to_string method for converting integers...
Why not simplify it and do it this way: Where (Fullweek = 1) -- Will get all days of week or (Fullweek = 0 and datepart(dw,date) in (2,3,4,5,6)) ...
Keeping aside any other issue, your code produces undefined behaviour, at least. In your getYear() function, you're trying to return the address of a local variable buf. This is not possible. Instead, you can define buf as char pointer. allocate memory dyncamiccly using malloc()/calloc() use and return buf from getYear()...
Integer values are just numbers, they don't include formatting. However, when you print them, you can format them. Example: Console.WriteLine("You guessed {0:N0}.", guess); With my regional setttings, prints: 500,000 See this overload of Console.WriteLine and here's the list of standard numeric formatting strings....
Java primitives (int, long, boolean, etc) are not references, they're actual values. When you have addOneTo(y);, addOneTo receives a copy of the value. That copied value is incremented by one, and then lost when the method exits. As an analogy, when you see a primitive method parameter you can think...
int test= Integer.parseInt(str, 10); Is working nice for me... String str = "02"; int test= Integer.parseInt(str, 10); System.out.println(">"+test); Output: 2 If you don't put radix can be interpreted as octal... but in my computer output is correct. Double check if you are not executing in background another conversion......
java,matrix,int,java.util.scanner
If that's the actual file content it looks like you're exceeding the bounds of your array when it reads in 3 20 There is no [3][20] allocated in life, it would only go out to [3][19]. This is being obscured by your try/catch block which catches and drops the ArrayIndexOutOfBoundsException....
c,pointers,floating-point,int,type-conversion
This is not correct. int and float are not guaranteed to have the same alignment. Remember: Casting a value and casting a pointer are different scenarios. Casting a pointer changes the way to refer to the type value, which can almost certainly result in a mis-alignment in most of the...
It will be always TRUE only in this scenario When the value stored in ix with 'int' function, it will ignore the float values and just consider the whole number before the decimal point. In case of Floor, it will convert to the nearest lower whole number. The only difference...
Get the input and convert that to string array using split method, Iterate over that array of string and convert each string to char array. Please see the below code String str = "12 3 1 265"; String[] strArray = str.split(" "); for(String s : strArray){ char[] charArray = s.toCharArray();...
char is a fundamental data type, of size 1 byte (not necessarily 8bits!!!), capable of representing at least the ASCII code range of all characters. So, for example, char x = 'a'; really stores the ASCII value of 'a', in this case 97. However, the ostream operators are overloaded so...
the most reliable method of handling very large numbers is to use the 'bignum.c', which is available at: http://www3.cs.stonybrook.edu/~skiena/392/programs/bignum.c the referenced code is a complete program,. but the functions and struct are free to use. where is what you would find there: /* bignum.c Implementation of large integer arithmetic: addition,...
You could populate a list and shuffle it: List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Collections.shuffle(numbers); int coin1 = numbers.get(0); int coin2 = numbers.get(1); ...