我试图来计算1 + 1 * 2 + 1 * 2 * 3 + 1 * 2 * 3 * 4 + ... + 1 * 2 * ... * n
,其中n
是用户输入.它适用于中值n
高达12.我要计算总和n = 13
,n = 14
和n = 15
.我如何在C89中做到这一点?据我所知,我unsigned long long int
只能在C99或C11中使用.
我的代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned long int n;
unsigned long int P = 1;
int i;
unsigned long int sum = …
Run Code Online (Sandbox Code Playgroud) 我有下一个我想读取2D数组的代码.它会这样做,但在程序结束后,程序每次都会崩溃.我有一个更大的计划,但这是唯一的问题.我还阅读了正确分配多维数组并调试了程序.
问题是:为什么程序在最后崩溃,即使它在整个预期的操作程序中运行正常?
void dynamicMemAlloc(int n, int (**arrayPointer)[n][n]){
*arrayPointer = malloc(sizeof(int[n][n]));
assert(*arrayPointer != NULL);
}
void readMy2Darray(int n, int array[n][n]){
int i, j;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
scanf("%d", &array[i][j]);
}
void printMy2Darray(int n, int array[n][n]){
int i, j;
for(i = 1; i <= n; i++){
for(j = 1; j <= n; j++)
printf("%d ", array[i][j]);
printf("\n");
}
}
int main(void){
int n;
printf("Read the dimension(n): ");
scanf("%d", &n);
int …
Run Code Online (Sandbox Code Playgroud) 我想在Visual Studio 2017中选择一段代码并对其进行评论.我知道我可以使用CTRL + K,C,但结果是:
/*fstream in("c:\\users\\hp\\documents\\visual studio 2017\\projects\\inputfile.in");
if (!in)
{
cerr << "can't open input file\n";
return 1;
}
fstream out("outputfile.out", fstream::out);
if (!out)
{
cerr << "can't open output file\n";
return 1;
}*/
Run Code Online (Sandbox Code Playgroud)
而我真正想要的是
//fstream in("c:\\users\\hp\\documents\\visual studio 2017\\projects\\inputfile.in");
//if (!in)
//{
// cerr << "can't open input file\n";
// return 1;
//}
//fstream out("outputfile.out", fstream::out);
//if (!out)
//{
// cerr << "can't open output file\n";
// return 1;
//}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
我搜索了互联网,但我找不到这个问题的答案.
我的代码有问题.malloc
在while循环中realloc()
工作,第一次工作,第二次调用时,它总是失败.该代码是获取数字素因子的算法的一部分.
int main()
{
int n, in, *ar, len = 0;
scanf("%d", &n);
ar = (int *) malloc(1 * sizeof(int));
while(n % 2 == 0){
ar[len] = 2;
len++;
ar = (int *) realloc(ar, len * sizeof(int));
if(ar == NULL){
printf("Error");
return 1;
}
n /= 2;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我尝试len
初始化为1但它仍然失败.奇怪的是它在第一次通话时没有失败,但在第二次通话时失败了.我读过其他类似的问题,但我是初学者,我不明白.提前致谢!
奇数数组以这种方式分组:first
数字是第一组,下一个2
数字形成第二组,下一个3
数字形成第三组,依此类推.
团体:
现在我想查找给定数字是否是组中数字的总和并找到该组的订单号.
我写了下一个代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int k;
scanf("%d", &k);
int x = 1;
while( x * x * x < k )
x++;
if( x * x * x != k )
x = 0;
printf("%d", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后我尝试将while
循环更改为下一个循环:
while( x * x * x++ < k )
; …
Run Code Online (Sandbox Code Playgroud)