编辑#3:所以当我用gcc编译时,一切正常.如果我使用clang(版本3.0),它只给我0.我很困惑为什么clang不会为此工作,因为它似乎相对简单.
编辑#2:好的,所以我已经确认感谢大家代码确实有效,但它可能就是环境.我正在使用ARM三星Chromebook在Ubuntu上做这一切(实际上是通过chroot).我正在使用clang 3.0(只有-o标志)来编译所有内容.我在vim中输入所有内容.是因为我在ARM上发生了这种情况吗?
我一直盯着这看了两个小时,不能抓住我的错误.无论我做什么,Float似乎都会返回0.000000.我试过除以10000.0,将10000存储在float类型的变量中,类型为double.
我甚至编写了一个小程序,它只有一个float类型的变量,存储了1.1,然后是printf("%f",变量),打印0.000000.
编辑:忘了提到1.1就在那里,因为我只是测试漂浮..我知道我必须除以10000,哈哈.
我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
bool diceRoll (int a)
{
int n = 0;
int b = 0;
while(n < 1) {
b = rand() % 12;
if(b == a || b == 6) n++;
}
if(b == 6) return false;
else return true;
}
int main (void)
{
srand( (unsigned)time(NULL));
int a, n, house, player;
float houseWinRate, playerWinRate;
house = 0;
player = 0;
float total = 1.1;
for(n …Run Code Online (Sandbox Code Playgroud) 我试图通过for循环递增计数器来打开不同的文件,然后将该计数器附加到要打开的文件名,但我仍然坚持如何使用strcat来执行此操作.如果我理解正确,strcat需要2个字符串,但我的计数器是一个int.我怎样才能使它成为一个字符串?
for(a = 1; a < 58; a++) {
FILE* inFile;
int i;
char filename[81];
strcpy(filename, "./speeches/speech");
strcat(filename, a);
strcat(filename, ".txt");
Run Code Online (Sandbox Code Playgroud)
绝对不起作用,因为a是一个int.当我尝试将它转换为char时,因为从1开始并且到57,我得到所有错误的值,因为1处的char实际上不是数字1 ..我被卡住了.
我在将文本转换为char数组时遇到了一些麻烦.当我为数组设置静态大小时,它工作正常
char speech[15000];
Run Code Online (Sandbox Code Playgroud)
但这样效率很低,所以我尝试使用calloc.这使它停止工作.数组的大小合适,但没有任何内容写入.这是相关的代码.我究竟做错了什么?
int main() {
FILE* inFile;
int i;
int count = 0;
printf("\nOpening file April_30_1789.txt\n");
inFile = fopen("./speeches/April_30_1789.txt", "r");
if(inFile == NULL) {
printf("Could not find April_30_1789.txt\n");
return -1;
}
char ch;
while((ch = fgetc(inFile) != EOF)) count++;
rewind(inFile);
int size = count;
printf("Size of the array is %d\n", size);
char *speech = (char *)malloc(size*sizeof(char) + 1*sizeof(char));
fscanf(inFile, "%s", speech);
printf("Closing the file.\n");
fclose(inFile);
printf("%s", speech);
printf("\n\nDone\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
目前,这给了我
Opening file April_30_1789.txt
Size of the …Run Code Online (Sandbox Code Playgroud) 例如,如果我输入"qwer",这会让我输出"呃".如果我只要求userIn [2],如何输出"r"?
另外,"char userIn [256]"是否有一个较不脏的替代品?我看到它的方式,256限制预先确定用户可以输入什么,这是不好的.但我不知道如何使userIn没有预定的大小.
char userIn[256];
printf("Type the message to be encoded: ");
scanf("%s", &userIn);
printf("\n");;
printf("This was typed: %s\n", &userIn[2]);
Run Code Online (Sandbox Code Playgroud)